Grouping items in a foreach loop in PHP
grouping, loops, php
Solution
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>';
}
Problem
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?