我需要对数组中的子数组中的一些值求和。
我有这个数组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
)
)
我想做的是对每个子数组中key[4]中的所有字段求和,并能够在$total;
中返回总数在这个例子中,$total;
等于4830
(960+3870)。
而且,当用户提交更多的产品时,数组可以包含比这2个更多的子数组。
<?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;
实际操作