2016-05-31 15 views
-1

i haben diese Array wie folgt:PHP Array: sum Elemente der Arrays

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

Ich würde die zurückgegebene Array wie das gleiche sein, aber der Schlüssel „total“ nicht zu einem aArray sein, aber die Summe von alle precedemtn Wert wie folgt aus:

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

PS: die Anzahl der Elemente in der „Gesamt Array“ Jede Hilfe kann sich ändern? thx im Voraus

+0

und wo genau das Problem ist, dass Sie von der Verwendung einer einfachen Schleife oder irgendeine andere Art und Weise ein Array zusammenzufassen verhindert? – Sirko

+2

[array_sum] (http://www.w3schools.com/php/func_array_sum.asp) scheint einfach genug zu sein –

Antwort

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

Sie können dies versuchen:

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

Sie können diesen Code versuchen.

<?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); 
0
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4); 
echo "sum(b) = " . array_sum($b); 
*Output* : sum(b) = 6.9