按键汇总数组值

时间:2013-03-01 17:01:47

标签: php arrays multidimensional-array

我需要从数组中的子数组中总结一些值。

我有这个数组

Array
(
    [smecid_2] => Array
        (
            [0] => 1
            [1] => SMEC 55.6
            [2] => 960
            [3] => 864
            [4] => 960
            [5] => 864
        )

    [smecid_6] => Array
        (
            [0] => 3
            [1] => SMEC 55.6 ATEX EX
            [2] => 1290
            [3] => 1161
            [4] => 3870
            [5] => 3483
        )

)

我想要做的是总结每个子阵列的键[4]中的所有字段,并能够回显$ total中的总数;

在此示例中,$total;4830(960 + 3870)。

此外,当用户提交更多产品以供订购时,阵列可以容纳更多子阵列。

1 个答案:

答案 0 :(得分:1)

<?php
$array = array
(
    'smecid_2' => array
        (
            0 => 1,
            1 => 'SMEC 55.6',
            2 => 960,
            3 => 864,
            4 => 960,
            5 => 864,
        ),

    'smecid_6' => array
        (
            0 => 3,
            1 => 'SMEC 55.6 ATEX EX',
            2 => 1290,
            3 => 1161,
            4 => 3870,
            5 => 3483,
        )

);

$sum = 0;
foreach ($array as $subarray)
{
    $sum += $subarray[4];
}
echo $sum;

See it in action