Grouping SQL Result Set in PHP

Let's say I have a request to execute the following request:

Edit

The order is added because the real sql statement has one.

SELECT description, amount, id FROM table ORDER BY id 

In this case, the identifier is not unique to the dataset. This will return something like this.

  Description Amount ID ----------- ------ -- 1 Hats 45 1 2 Pants 16 1 3 Shoes 3 1 4 Dogs 5 2 5 Cats 6 2 6 Waffles 99 3 

What I need to do is enclose each section of identifiers in its own div (so that lines 1,2,3 in one div, 4,5 in another div and 6 in it own div).

There are many solutions for this, but I just can't think of which is not too difficult.

I want to be able to store SQL like this and somehow sort the data set in PHP so that I can scroll through each section of the data set, making my way through the data set as a whole.

Some kind of array will work, but its structure forces me.

How can I make this work? PHP solutions will be an idea, but theoretical help will help too.

+4
source share
4 answers

A simple consistent solution might look something like this:

 $curId = ''; // track working id $firstDiv = true; // track if inside first div // open first div echo '<div>'; // foreach $row { // when id changes, transition to new div, except when in first div if ($row->$id != $curId) { if ($firstDiv) { $firstDiv = false; } else { // start new div echo '</div>'; echo '<div>'; } $curId = $row->$id; // track new current id } // display contents of current row } // close last div echo '</div>'; 
+3
source

See if something like this works.

 // execute query: Select description, amount, id from table $results = array(); while ($row = $query_result->fetch_array()) { if (!isset($results[$row['id']])) $results[$row['id']] = array(); $results[$row['id']][] = $row; // push $row to results for this id } // later on foreach($results as $id => $data) { // output div based on $id foreach($data as $datum) { // output individual data item that belongs to $id } } 
+4
source

Just save the id in temp variable if the next other closes the div and open a new div

+1
source

Assuming associative arrays for db results:

 $final = array(); foreach($results as $result) { $final[$result['id']][] = $result; } 

This gives you the $final associative array, which groups the entries by id

+1
source

All Articles