Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 539015
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:05:32+00:00 2026-05-13T10:05:32+00:00

This is a problem I have run into before and I have yet to

  • 0

This is a problem I have run into before and I have yet to find an elegant solution, so I thought I would ask for SO’s help.

I am iterating through an array and printing off some information from that array and having trouble figuring out how to print my start and end <div> tags. Below is an example table and the desired output along with a basic implementation of my current algorithm. I am hoping that somebody can point me to a better algorithm for printing the data. I’m doing it in PHP, but a generic algorithm would be wonderful.

Thanks very much!

Table: (spacing added for clarity)

Choice ID     Choice Body     Question ID     Question Body
---------------------------------------------------------------------
1             Yes, very much  1               Do you like sandwiches?
2             Somewhat        1               Do you like sandwiches?
3             Not at all      1               Do you like sandwiches?
4             I hate them     1               Do you like sandwiches?

5             Sure, why not   2               Do you like apples?
6             Yesh, I guess   2               Do you like apples?
7             What are those  2               Do you like apples?

8             Yes, very much  3               Do you like chips?
9             Not at all      3               Do you like chips?

Desired Output:

<div class='question' id='1'>
  <p>Do you like sandwiches?</p>

  <div class='choices'>
    <span class='choice'>Yes, very much</span>
    <span class='choice'>Somewhat</span>
    <span class='choice'>Not at all</span>
    <span class='choice'>I hate them</span>
  </div>
</div>

<div class='question' id='2'>
  <p>Do you like apples?</p>

  <div class='choices'>
    <span class='choice'>Sure, why not</span>
    <span class='choice'>Yeah, I guess</span>
    <span class='choice'>What are those</span>
  </div>
</div>

<div class='question' id='3'>
  <p>Do you like chips?</p>

  <div class='choices'>
    <span class='choice'>Yes, very much</span>
    <span class='choice'>Not at all</span>
  </div>
</div>

Basic Algorithm I’m Currently Using:

$last_id = null;
while ($choice = pg_fetch_array($choices)) {
    if ($last_id != $choice['id']) {
        if ($last_id != null) {
          echo "</div>";
        }

        echo "<div id='$choice[id]'>";
    }

    // Print choice info

    $last_id = $choice['id'];
}

if ($last_id != null) {
    echo "</div>";
}

Note: The reason I’m using this way is for optimization purposes. This requires only one database query, and there are going to be a lot of results. I don’t want to have to do a query for each question to get it’s choices. I know how to do that, and it is easier, but not very efficient or fast.

Edit 1: Fixed code, the algorithm now works, but still isn’t pretty. For the commenter: pg_fetch_array() is a PostgreSQL function that basically creates an associative array. Very similar to an object. Allows you to just ask for the $choice['id'] or $choice['body'].

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T10:05:32+00:00Added an answer on May 13, 2026 at 10:05 am

    Grouping items by similar values can hardly be called an algorithm. It’s more of a coding pattern if anything else.

    A good way to code is to separate the mechanism from the intent. In this case the mechanism is how to keep track of the key values to find the grouping boundaries and the intent is to output HTML for each sequential group.

    Python for instance has a library function called groupby to do exactly this. So in Python the code would look something like this (ignoring the fact that one would use a templating library for this):

    from itertools import groupby
    
    def question_from_row(row):
        return dict(id=row['question_id'], body=row['question_body'])
    
    for question, choices in groupby(questions, key=question_from_row):
        print('<div class="question" id="%s">' % question['id'])
        print('  <p>%s</p>\n' % question['body'])
        print('  <div class="choices">')
        for choice in choices:
            print('<span class="choice">%s</span>' % choice['choice_body'])
        print('  </div>')
        print('</div>')
    

    PHP to my knowledge doesn’t have anything like that built in, but a naive implementation is pretty easy:

    function array_groupby($input, $keyfunc) {
        $output = array();
        $last_key = null;
        $current = null;
        foreach ($input as $item) {
            $item_key = $keyfunc($item);
            if ($last_key === null || $item_key != $last_key) {
                if ($current !== null) {
                    $output[] = $current;
                }
                $last_key = $item_key;
                $current = array();
            }
            $current[] = $item;
        }
        if ($current !== null) {
            $output[] = $current;
        }
        return $output;
    }
    

    This would be typical library code that you include in. The code that deals with the output then becomes rather trivial. Completely isolated from how the grouping is done. For instance you could change array_groupby to return an object that implements the Iterator interface and only lazily fetches from the input iterable.

    $questions = array_groupby(pg_fetch_array($choices),
        function($choice) { return $choice['id']; });
    
    foreach ($questions as $choices) {
        $question = $choices[0];
        echo '<div class="question" id="'.$question['id'].'">';
        echo '<p>'.$question['body'].'</p>';
        echo '<div class="choices">';
        foreach ($choices as $choice) {
            echo '<span class="choice">'.$choice['choice_body'].'</span>';
        }
        echo '</div>';
        echo '</div>';
    }
    

    This example is using the PHP 5.3 closures feature. On older versions specifying the function to extract the grouping key would be slightly uglier, perhaps calling for an object oriented approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 360k
  • Answers 360k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Calling finish() from the activity you want to end should… May 14, 2026 at 2:37 pm
  • Editorial Team
    Editorial Team added an answer Members are thread-safe, but you shouldn't expect a sequence of… May 14, 2026 at 2:37 pm
  • Editorial Team
    Editorial Team added an answer var array_of_objects = eval("[" + my_string + "]"); This executes… May 14, 2026 at 2:37 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.