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
Release: 2024-12-16 22:03:11
Original
1067 people have browsed it

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;
});
Copy after login

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

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

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);
Copy after login

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);
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template