PHP Array_Sum for a multidimensional array

If I have a multidimensional array in PHP, for example ...

[0] => Array ( [url] => http://domain1.com [domain] => domain1.com [values] => Array ( [character_length] => 25 [word_count] => 7 ) ) [1] => Array ( [url] => http://domain2.com [domain] => domain2.com [values] => Array ( [character_length] => 30 [word_count] => 7 ) 

How can I combine them to create ....

  [0] => Array ( [url] => *can be anything* [domain] => *can be anything* [values] => Array ( [character_length] => 55 [word_count] => 14 ) ) 
+4
source share
3 answers

Just make a simple foreach for all elements and summarize the values:

 $values = array( 'character_length' => 0, 'word_count' => 0 ); foreach ($array as $item) { $values['character_length'] += $item['values']['character_length']; $values['word_count'] += $item['values']['word_count']; } 
+5
source

I do not think that there is a built-in function that will allow you to summarize the values ​​of a multidimensional array. However, here you can do this using the lambda-style function.

Suppose this is your array:

  [items] => Array ( [0] => Array ( [ID] => 11 [barcode] => 234334 [manufacturer] => Dell [model] => D630 [serial] => 324233 [current_value] => 1100.00 ) [1] => Array ( [ID] => 22 [barcode] => 323552 [manufacturer] => Dell [model] => D630 [serial] => 234322 [current_value] => 1500.00 ) ) 

You can create a function that you could pass values ​​to:

 $array_value_sum = create_function('$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;'); 

And then use it like this:

 echo "Total Current Value" . $array_value_sum($obj['items'], 'current_value'); 
+7
source

You can do this using array_sum () and array_map () as shown below:

 $totalCharacterLength = array_sum(array_map(function($item) { return $item['values']['character_length']; }, $totalCharacterLength)); $totalWordCount = array_sum(array_map(function($item) { return $item['values']['word_count']; }, $totalWordCount)); 
0
source

All Articles