How to Sum Columnar Values in Multi-Dimensional Arrays
In multi-dimensional arrays, summarizing values along columns is a common task. Here's how it's done, considering the challenge of dynamic associative key sets:
General-Case Solution with array_walk_recursive
Using array_walk_recursive, you can consistently summarize columns regardless of key structure:
$final = array(); array_walk_recursive($input, function($item, $key) use (&$final){ $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item; });
array_column() for Exact Keys
From PHP 5.5 onwards, you can use array_column to efficiently summarize specific columns:
array_sum(array_column($input, 'gozhi')); // For 'gozhi' column
Total Sum for All Key Sets
If you want the aggregate sum of all inner arrays with matching keys (as in the desired output), use this approach:
$final = array_shift($input); foreach ($final as $key => &$value){ $value += array_sum(array_column($input, $key)); } unset($value);
General-Case Solution with array_column
A more advanced approach using array_column involves identifying all unique keys and then summarizing:
$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 Efficiently Sum Column Values in Multi-Dimensional PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!