0

假设我从查询结果中有这个数组:

[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      |
---------------------
4

1 回答 1

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>";
   }
}
于 2013-06-11T23:05:31.270 回答