Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping items in a foreach loop in PHP [duplicate]

So, I'm trying to make a sort of user-market type thing. There's a database with item_names, basically describes the virtual items, then there's another table market, where when a user lists one of their items, it's put for sale on the user-user market.

My only problem here is I want to group it by item name, referenced in the item_name table. I know I could do a bunch of if/else statements but that's extraneous not only because there's a lot of items, but also because I will add more items as time goes on. I want the end result to be something like

--[Water for sale]---------------------+

[50 water for sale] [20 water for sale]

[10 water for sale] [10 water for sale]

--[Chips for sale]----------------------+

[50 chips for sale] [20 chips for sale]

[10 chips for sale] [10 chips for sale]

And so on, done dynamically.

Any help?

like image 206
Urduni Avatar asked Dec 22 '25 23:12

Urduni


1 Answers

Fetch data:

$data = array();
while ($row = mysql_fetch_assoc($result)) {
  $itemName = $row["item_name"];
  if (!array_key_exists($itemName, $data)) {
    $data[$itemName] = array();
  }
  $data[$itemName][] = $row;
}

Display data

foreach ($data as $itemName => $rows) {
  echo '<h1>', $itemName, '</h1>';
  echo '<ul>';
  foreach ($rows as $row) {
    echo '<li>', $row["article_name"], '</li>';
  }
  echo '</ul>';
}
like image 93
MonkeyMonkey Avatar answered Dec 24 '25 19:12

MonkeyMonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!