Urduni
Urduni

Reputation: 31

Grouping items in a foreach loop in PHP

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?

Upvotes: 3

Views: 9968

Answers (2)

bfavaretto
bfavaretto

Reputation: 71908

Make sure you order (not group) the results on your SQL query, then the loop will be very simple (assuming PDO, and a column item_name on table item_names):

$sth = $dbh->query ("SELECT * FROM item_names ORDER BY item_name");
$lastname = '';
while ($row = $sth->fetch()) {
    if($lastname != $row['item_name']) {
        echo '<h1>' . $row['item_name'] . '</h1>';
    }
    // echo contents for each item here

    // remember name from last row
    $lastname = $row['item_name'];
}

Upvotes: 0

MonkeyMonkey
MonkeyMonkey

Reputation: 836

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>';
}

Upvotes: 6

Related Questions