Home >Backend Development >PHP Tutorial >How to Sum Column Values in Multi-Dimensional Arrays with Dynamic Keys in PHP?

How to Sum Column Values in Multi-Dimensional Arrays with Dynamic Keys in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 22:03:111069browse

How to Sum Column Values in Multi-Dimensional Arrays with Dynamic Keys in PHP?

Summing Column Values in Multi-Dimensional Arrays

Question:

How can you calculate the sum of column values in a multi-dimensional array, where the associative keys are dynamic?

Answer:

To sum column values in a multi-dimensional array with dynamic keys, you can utilize array_walk_recursive(). It provides a general solution for cases where each inner array has unique keys.

$final = array();

array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

For specific keys, array_column() is a suitable option, available since PHP 5.5.

array_sum(array_column($input, 'gozhi')); // for key 'gozhi'

To obtain the total sum of columns with the same keys, you can extract the first inner array as the base, sum the values for each key using array_column(), and add them to the base:

$final = array_shift($input);

foreach ($final as $key => &$value){
   $value += array_sum(array_column($input, $key));
}    

unset($value);

For a general solution using array_column(), consider first obtaining all unique keys and then calculating the 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 Column Values in Multi-Dimensional Arrays with Dynamic Keys in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn