Assume I have this array from a query results:
[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"}
How to make an HTML table which same group shows only once and make td rowspan
value in group field(category
) according to number of members?
Desired result:
--------------------
|fruit |banana |
| -----------
| |grape |
| -----------
| |pinapple |
--------------------
|animal |mouse |
| -----------
| |elephant |
| -----------
| |ant |
---------------------
Create a different array.
$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>";
}
}