0

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 rowspanvalue in group field(category) according to number of members?

Desired result:

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

1 Answer 1

2

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>";
   }
}
1
  • For second and next member we need adding new row (tr) Jun 13, 2013 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.