PHP数组:数组的和元素

时间:2016-05-31 12:11:40

标签: php arrays

我有这样的数组:

array(2)(
['id'] => "59898441545",
['total'] => 
array(
[0] => 2,
[1] => 5
[2] => 10
[3] => 35
)
);

我希望返回的数组是相同的,但是键#34;总数"不是aarray而是所有先前值的总和,如下:

array(2)(
['id] => "59898441545",
['total'] => 52 // the sum of the precedent elements
);

P.S:"总数组中的元素数量"可能会改变 有帮助吗? thx提前

4 个答案:

答案 0 :(得分:8)

$youarray['total'] = array_sum($youarray['total']);

答案 1 :(得分:1)

你可以试试这个:

$sum = 0;
foreach($mainArr['total'] as $arr) {
    $sum += $arr;
}
$mainArr['total'] = $sum;

答案 2 :(得分:1)

您可以尝试使用此代码。

<?php
$data = array('id' => "59898441545",
'total' => array(
        0 => 2,
        1 => 5,
        2 => 10,
        3 => 35
)
);
 $data['total'] = array_sum($data['total']);
echo "<pre>";print_r($data);

答案 3 :(得分:0)

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4); 
echo "sum(b) = " . array_sum($b);
*Output* : sum(b) = 6.9