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
Release: 2024-12-27 09:40:12
Original
487 people have browsed it

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

The desired outcome is:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)
Copy after login

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

array_column()

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

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

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

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

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template