将多维数组打印到表

时间:2017-12-26 12:11:30

标签: php html arrays multidimensional-array html-table

我有一个像这样的数组,

Array
(
    [0] => Array
        (
            [id] => 109
            [label] => c
            [quantity] => 12
            [unit] => g
        )

    [1] => Array
        (
            [id] => 120
            [label] => c
            [quantity] => 12
            [unit] => g
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
            [id] => 119
            [label] => b
            [quantity] => 200
            [unit] => oz
        )

)

Array
(
    [0] => Array
        (
            [id] => 118
            [label] => b
            [quantity] => 200
            [unit] => oz
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

)

Array
(
    [0] => Array
        (
            [id] => 121
            [label] => b
            [quantity] => 10
            [unit] => g
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

)

我必须打印

<table>
<tr><td>c</td><td>c</td><td></td><td></td><td>b</td></tr>
<tr><td>b</td><td></td><td></td><td></td><td></td></tr>
<tr><td>b</td><td></td><td></td><td></td><td></td></tr>
</table>

我尝试的是,

foreach($final_array as $food_array){
echo '<tr>';
echo '<td>'.$food_array[0]['label'].'</td>';
echo '<tr>';
}

但它似乎不起作用,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

以下是您应该尝试的代码,

foreach ($final_array as $food_array) {
    echo '<tr>';
    foreach ($food_array as $key1 => $value1) {
        echo '<td>' . $value1['label'] . '</td>';    
    }
    echo '<tr>';
}

您需要将其循环两次才能获得输出。