Jump to content

Archived

This topic is now archived and is closed to further replies.

MrMastermind

Display array table grouped by array value

Recommended Posts

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??

Share this post


Link to post
Share on other sites
Is the data being called from a db?

If not, then may I recommend [url=http://us2.php.net/usort]usort()[/url]

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
[quote author=MrMastermind link=topic=112579.msg456994#msg456994 date=1161721854]
If you have an example, that would be great![/quote]

Did you click that link he provided. There are examples there.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
Assuming $results is the array, this should be close to what you are looking for.

[code]
$currentGroup = "";

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

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.