计算数组中的值

时间:2016-01-08 16:05:17

标签: php arrays

我试图从这个数组中获取值并计算它们。假设我们有阿姆斯特丹,我想将价值[41,21,43]计算在一起并将它们放在一个html表格中。问题是这些值有时会错过,如下所示。我怎样才能做到这一点?

Array
(
    [Amsterdam] => Array
        (
            [41] => 2
            [21] => 91
            [43] => 16
            [42] => 2
            [20] => 30
            [4] => 4
            [70] => 3
            [84] => 8
            [46] => 4
            [45] => 5
            [999] => 26
            [47] => 2
            [3] => 8
            [44] => 1
            [40] => 1
            [93] => 5
            [56] => 3
            [61] => 3
            [79] => 3
            [48] => 2
            [50] => 5
            [10] => 10
            [52] => 2
            [120] => 1
            [95] => 1
            [1] => 64
            [90] => 4
            [100] => 2
            [101] => 1
        )

    [Rotterdam] => Array
        (
            [21] => 42
            [41] => 2
            [42] => 2
            [46] => 1
            [47] => 2
            [43] => 4
            [45] => 3
            [4] => 1
            [3] => 19
            [84] => 1
            [12] => 1
            [20] => 14
            [40] => 1
            [48] => 6
            [61] => 1
            [52] => 1
            [10] => 4
            [1] => 23
            [90] => 2
        )

    [Spaarnwoude] => Array
        (
            [21] => 2
        )

这是我已经尝试过的:

  foreach ($headings as $h) {
        echo "<th>$h</th>";
    }
    echo '</tr>';

    foreach($cities as $cityname => $city) { 
        echo '<tr>';
        echo "<td>$cityname</td>";
        foreach (array_chunk($headings, 3) as $h) {
            echo '<td>' . (isset($city[$h]) ? $city[$h] : '0') . '</td>';
        }    
        echo '</tr>';
    }

    echo '</table>';

有关详细信息,请查看此链接。

How to get array output in html table

1 个答案:

答案 0 :(得分:1)

您需要为块中的每个标题进行另一级循环。

$chunked_headings = array_chunk($headings, 3);
echo '<tr>';
foreach ($chunked_headings as $heading_group) {
    echo '<th>' . implode(', ', $heading_group) . '</th>';
}
echo '</tr>';

foreach ($cities as $cityname => $city) {
    echo '<tr>';
    echo "<td>$cityname</td>";
    foreach ($chunked_headings as $heading_group) {
        $total = 0;
        foreach ($heading_group as $h) {
            if (isset($city[$h])) {
                $total += $city[$h];
            }
        }
        echo "<td>$total</td>";
    }
}