【问题标题】:How to show list result follow format table [duplicate]如何显示列表结果遵循格式表[重复]
【发布时间】:2015-11-21 06:09:09
【问题描述】:

我有一个通过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

【问题讨论】:

    标签: php mysql html-table


    【解决方案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>";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      相关资源
      最近更新 更多