Home >Backend Development >PHP Tutorial >How to Sum Columnar Values in Multi-Dimensional PHP Arrays?

How to Sum Columnar Values in Multi-Dimensional PHP Arrays?

DDD
DDDOriginal
2024-12-27 09:40:12490browse

How to Sum Columnar Values in Multi-Dimensional PHP Arrays?

Adding Columnar Values in Multi-Dimensional 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:

array_walk_recursive()

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;
});

array_column()

For specific keys (e.g., "gozhi"), use array_column() (available since PHP 5.5):

array_sum(array_column($input, 'gozhi'));

For Arrays with Identical Keys

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);

General-Case Solution with array_column()

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!

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