2013-06-11 65 views
0

假設我有從查詢結果此數組:組行從PHP陣列

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

回答

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>"; 
    } 
} 
+0

對於第二個和下一個成員,我們需要添加新行('tr') –