Home >Backend Development >PHP Tutorial >How to Efficiently Calculate Column Totals in Irregular Multi-Dimensional Arrays?
How to Calculate Column Totals in a Multi-Dimensional Array
Consider a multi-dimensional array where elements are arranged in rows and columns, but the key sets may vary dynamically. The task is to calculate the sum of values within each column, regardless of key variations.
Array_Walk_Recursive Method
For a general solution where inner arrays can have unique keys, utilize array_walk_recursive():
$final = array(); array_walk_recursive($input, function($item, $key) use (&$final){ $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item; });
Array_Column Method
If specific key values need to be summed, array_column() can be used:
array_sum(array_column($input, 'gozhi')); // Sums the 'gozhi' column
For Uniform Inner Arrays
If all inner arrays have the same keys, obtain the initial key structure:
$final = array_shift($input); foreach ($final as $key => &$value){ $value += array_sum(array_column($input, $key)); } unset($value);
General Case with Array_Column
Extract unique keys and perform column sums:
$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 Calculate Column Totals in Irregular Multi-Dimensional Arrays?. For more information, please follow other related articles on the PHP Chinese website!