Home >Backend Development >PHP Tutorial >How to Sum Columnar Values in Multi-Dimensional PHP Arrays?
You're aiming to sum the values associated with specific keys in a multi-dimensional array with varying key sets. Consider the following input:
Array ( [0] => Array ( [gozhi] => 2 [uzorong] => 1 [ngangla] => 4 [langthel] => 5 ) [1] => Array ( [gozhi] => 5 [uzorong] => 0 [ngangla] => 3 [langthel] => 2 ) [2] => Array ( [gozhi] => 3 [uzorong] => 0 [ngangla] => 1 [langthel] => 3 ) )
The desired outcome is:
Array ( [gozhi] => 10 [uzorong] => 1 [ngangla] => 8 [langthel] => 10 )
To achieve this, consider the following approaches:
For a general-case solution, use array_walk_recursive():
$final = array(); array_walk_recursive($input, function($item, $key) use (&$final){ $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item; });
For specific keys (e.g., "gozhi"), use array_column() (available since PHP 5.5):
array_sum(array_column($input, 'gozhi'));
If all inner arrays have the same keys:
$final = array_shift($input); foreach ($final as $key => &$value){ $value += array_sum(array_column($input, $key)); } unset($value);
Get all unique keys and then sum for each:
$final = array(); foreach($input as $value) $final = array_merge($final, $value); foreach($final as $key => &$value) $value = array_sum(array_column($input, $key)); unset($value);
The above is the detailed content of How to Sum Columnar Values in Multi-Dimensional PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!