Your array is bad designed. How should one know, that apples
is the same as apple
. Your array should be constructed this way:
$fruits['apples']['blue'] = 24;
$fruits['apples']['read'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
Then iterating is easy. The first level of the array are the rows. So:
<?php
$column_head = array();
foreach($fruits as $key => $value) {
$column_head = array_merge($column_head, array_keys($value));
}
$column_head = array_unique($column_head);
print_r($column_head);
?>
<table>
<tr>
<th></th>
<?php foreach($column_head as $head): ?>
<th><?php echo $head; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($fruits as $fruit => $amount): ?>
<tr>
<td><?php echo $fruit ?></td>
<?php foreach($column_head as $head): ?>
<td><?php echo isset($amount[$head]) ? $amount[$head] : 0 ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This generates which columns to use on fly, but it can be hardcoded which might be easier. As the code uses a lot loops it might be not that efficient...