views:

64

answers:

2

how do it turn a multidimensional array like:

$fruits['apples']['blue'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['apple']['red'] = 34;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;

into a cross referenced table like:

alt text

Thanks!

+2  A: 
$cols = array('blue', 'red', 'orange');
echo '<table>';
echo '<thead><tr><td></td><th scope="col">' . implode('</th><th scope="col">', $cols) . '</th></tr></thead>';
echo '<tbody>';
foreach($fruits as $label => $row)
{
    echo '<tr>';
    echo '<th scope="row">' . $label . '</th>';
    foreach($cols as $k)
    {
      echo '<td>' . (isset($row[$k]) ? $row[$k] : 0) . '</td>';
    }
    echo '</tr>';
}
echo '</tbody>';
echo '</table>';

You’ll want some HTML escaping and such, but that’s the gist of it.

Mo
awesome, thankyou!
significance
instead of writing $cols = array('blue', 'red', 'orange');, the code should know the colors array as well. This means one extra foreach to get the colors first.
marvin
A: 

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

Felix Kling