如何显示列表结果遵循格式表

时间:2015-08-27 02:08:09

标签: php mysql html-table

我在mysql查询后有一个列表产品

product_id | product_name | group_id | group_name
    1            ABC              1            A
    2            DEF              1            A
    3            GHI              1            A
    4            JKL              2            B  

我的代码

<table>
   <thead>
      <tr>
          <th>Group</th>
          <th>Product Name</th>
      </tr>
   </thead>
   <tbody>
   <?php foreach ($products as $product) : ?>
      <tr>
         <td><?php echo $product->group_name ?></td>
         <td><?php echo $product->product_name ?></td>    
      </tr>
   <?php endforeach; ?>
   </tbody>
</table>

结果

Group  | Product Name
A           ABC
A           DEF   
A           GHI
B           JKL

如何更改它以显示此结果

A
---
ABC
DEF
GHI

B
---
JKL

1 个答案:

答案 0 :(得分:1)

按组名称重新索引您的产品:

$productsByGroup = array();

foreach($products as $product) {
    if(!isset($productsByGroup[$product->group_name])) {
        $productsByGroup[$product->group_name] = array();
    }

    $productsByGroup[$product->group_name][] = $product;
}

foreach($productsByGroup as $group_name => $products) {
    print $group_name;
    print "<br>---<br>";
    foreach($products as $product) {
        print $product . "<br>";
    }
}