从多维数组php交叉引用表?

时间:2010-03-17 11:07:00

标签: php multidimensional-array

如何将多维数组转换为:

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

进入交叉引用表,如:

alt text http://1updesign.org/uploads/p24.png

2 个答案:

答案 0 :(得分:3)

$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>';

你会想要一些HTML转义等等,但这就是它的要点。

答案 1 :(得分:0)

您的阵列设计糟糕。如何知道,applesapple相同。你的数组应该这样构造:

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

然后迭代很容易。数组的第一级是行。所以:

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

这会生成要在飞行中使用的列,但它可以是硬编码的,这可能更容易。由于代码使用了很多循环,因此效率可能不高......