PHP数组中的HTML表格中的组行

时间:2013-06-11 23:01:15

标签: php html arrays

假设我从查询结果中获得此数组:

[0]=> { ["category"]=> "fruit" ["value"]=> "banana"} 
[1]=> { ["category"]=> "fruit" ["value"]=> "grape"}
[2]=> { ["category"]=> "fruit" ["value"]=> "pineapple"}    
[3]=> { ["category"]=> "animal" ["value"]=> "mouse"}    
[4]=> { ["category"]=> "animal" ["value"]=> "elephant"}    
[5]=> { ["category"]=> "animal" ["value"]=> "ant"}   

如何制作同一组只显示一次的HTML表格,并根据成员数量在组字段(td rowspan)中设置category值?

期望的结果:

--------------------
|fruit   |banana   |
|        -----------
|        |grape    |
|        -----------
|        |pinapple |
--------------------
|animal  |mouse    |
|        -----------
|        |elephant |
|        -----------
|        |ant      |
---------------------

1 个答案:

答案 0 :(得分:2)

创建一个不同的数组。

$truecats = array();
foreach ($cats as $pieces) {
    if (!isset($truecats[$pieces['category']]) {
        $truecats[$pieces['category']] = array();
    }
    $truecats[$pieces['category']][] = $pieces['value'];
}

// You can then loop over this array:

foreach ($truecats as $name => $values) {
   echo "<tr><td rowspan=" . count($values) . ">$name</td>";
   foreach ($values as $val) {
      echo "<td>$val</td>";
   }
}