PHP数组:数组的元素总和

PHP数组:数组的元素总和,php,arrays,Php,Arrays,我有这样一个数组: array(2)( ['id'] => "59898441545", ['total'] => array( [0] => 2, [1] => 5 [2] => 10 [3] => 35 ) ); array(2)( ['id] => "59898441545", ['total'] => 52 // the sum of the precedent elements ); 我希望返回的数组是相同的,但键“total”不是

我有这样一个数组:

array(2)(
['id'] => "59898441545",
['total'] => 
array(
[0] => 2,
[1] => 5
[2] => 10
[3] => 35
)
);
array(2)(
['id] => "59898441545",
['total'] => 52 // the sum of the precedent elements
);
我希望返回的数组是相同的,但键“total”不是aarray,而是所有PrecedMTN值的总和,如下所示:

array(2)(
['id'] => "59898441545",
['total'] => 
array(
[0] => 2,
[1] => 5
[2] => 10
[3] => 35
)
);
array(2)(
['id] => "59898441545",
['total'] => 52 // the sum of the precedent elements
);
备注:“总数组”中的元素数可能会改变 有什么帮助吗?thx提前

您可以尝试以下方法:

$youarray['total'] = array_sum($youarray['total']);
$sum = 0;
foreach($mainArr['total'] as $arr) {
    $sum += $arr;
}
$mainArr['total'] = $sum;
你可以试试这个代码

<?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);

问题到底出在哪里,它阻止您使用简单循环或任何其他方式对数组求和?看起来很简单