PHP/MySQL group results by column

18,286

Solution 1

Like mluebke commented, using GROUP means that you only get one result for each category. Based on the list you gave as an example, I think you want something like this:

$sql = "SELECT * FROM products WHERE category IN (10,120,150,500) GROUP BY category ORDER BY category, id";
$res = mysql_query($sql);

$list = array();
while ($r = mysql_fetch_object($res)) {
  $list[$r->category][$r->id]['name'] = $r->name;
  $list[$r->category][$r->id]['whatever'] = $r->whatever;
  // etc
}

And then loop through the array. Example:

foreach ($list as $category => $products) {
  echo '<h1>' . $category . '</h1>';

  foreach ($products as $productId => $productInfo) {
    echo 'Product ' . $productId . ': ' . $productInfo['name'];
    // etc
  }

}

Solution 2

Nope, I think your solution is the best for this problem. It seems that what's important for you is the output later on, so you should stick with your approach.

Share:
18,286
Adam Kiss
Author by

Adam Kiss

O HI

Updated on June 22, 2022

Comments

  • Adam Kiss
    Adam Kiss almost 2 years

    in order to keep as few SQL statements as possible, I want to do select set from MySQL:

    SELECT * FROM products WHERE category IN (10,120,150,500) ORDER BY category,id;
    

    Now, I have list of products in following manner:

    CATEGORY
     - product 1
     - product 2
    CATEGORY 2
     - product 37
    ...
    

    What's the best and most efficent way to process MySQL result?

    I thought something like (pseudo PHP)

    foreach ($product = fetch__assoc($result)){
      $products[$category][] = $product;
    }
    

    and then when outputting it, do foreach loop:

    foreach($categories as $category){
      foreach($products[$category] as $product){
        $output;
      }
    }
    

    Is this the best, or is something magical like mysql_use_groupby or something?