Jump to content


Photo

Display array table grouped by array value


  • Please log in to reply
5 replies to this topic

#1 MrMastermind

MrMastermind
  • Members
  • PipPip
  • Member
  • 23 posts

Posted 24 October 2006 - 08:17 PM

I'm trying to display results from an array in an HTML table, but I want to group the results by a value in the array. Something like:

array[
[id, title, groupname, date]
[id, title, groupname, date]
]

And then, group by the groupname. So that I can wrap each group in a DIV to display and hide the rest of the info. How would I loop through the array to group the info??

#2 Caesar

Caesar
  • Members
  • PipPipPip
  • Advanced Member
  • 1,025 posts

Posted 24 October 2006 - 08:20 PM

Is the data being called from a db?

If not, then may I recommend usort()
PHP Ninja

#3 MrMastermind

MrMastermind
  • Members
  • PipPip
  • Member
  • 23 posts

Posted 24 October 2006 - 08:30 PM

Thanks!

Not it is not called from a db, it's an array of data. I'll have a look at usort().

If you have an example, that would be great!

#4 Psycho

Psycho
  • Moderators
  • Move along, nothing to see here
  • 11,892 posts
  • LocationCanada

Posted 24 October 2006 - 08:45 PM

If you have an example, that would be great!


Did you click that link he provided. There are examples there.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

#5 MrMastermind

MrMastermind
  • Members
  • PipPip
  • Member
  • 23 posts

Posted 24 October 2006 - 08:56 PM

Yes, I did click the link. But maybe I don't understand it correctly. But usort() will sort my array. This helps a bit, but then I still have to loop through the array (using a foreach()) and compare values to either start a new div and table or to add a row to the current table.
So, I can sort of explain what I want to achieve, but can't get my head around it to write the code...

#6 Psycho

Psycho
  • Moderators
  • Move along, nothing to see here
  • 11,892 posts
  • LocationCanada

Posted 25 October 2006 - 04:21 PM

Assuming $results is the array, this should be close to what you are looking for.

$currentGroup = "";

foreach ($results as $row) {
  if ($row[groupname] != $currentGroup) {
    if ($currentGroup != "") { echo "</div>"; }
    echo "<div>";
    $currentGroup = $row[groupname];
  }
  echo $row[groupname] . "<br>";
}
echo "</div>";

The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users