I have a PHP array which has several different fields. For some of the rows id and name is the same and the rest of data is different.
I want to display the data in an HTML table without listing the duplicated data more than once. I realize that I can use colspan/rowspan to merge the table cells, but I'm not sure how to do counts/sums based on the matching values.
Below is how my table looks like :
Id Name value1 value2 value3
2312 ABC test test2 test3
2312 ABC XYz 122 211
2455 XYZ val11 val2 val3
Any help will be appreciated.
I can suggest you to create a new multidimensional array and merge the arrays that have the same ID ... the rest will be easy. Take a look at the example I've made
<?
$init_array = array(
array('id'=>2312, 'name'=>'ABC', 'value1'=>'asda', 'value2'=>'sdf', 'value3'=>'dfg'),
array('id'=>2312, 'name'=>'ABC', 'value1'=>'asd', 'value2'=>'fgd', 'value3'=>'ret'),
array('id'=>2455, 'name'=>'XYZ', 'value1'=>'sdgg', 'value2'=>'rew', 'value3'=>'gdg'),
);
$formatted_array = array();
foreach( $init_array as $element ) {
$formatted_array[ $element['id'] ][] = $element;
}
?>
<table border="2">
<? foreach($formatted_array as $row ): ?>
<tr>
<td rowspan="<?=count($row)?>"><?=$row[0]['id']?></td>
<td rowspan="<?=count($row)?>"><?=$row[0]['name']?></td>
<? foreach( $row as $value ): ?>
<td><?=$value['value1']?></td>
<td><?=$value['value2']?></td>
<td><?=$value['value3']?></td>
</tr><tr>
<? endforeach; ?>
</tr>
<? endforeach; ?>
</table>
the example in CodePad