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

How to Efficiently Sum Column Values in Multi-Dimensional PHP Arrays?

Patricia Arquette
Release: 2024-12-29 17:05:11
Original
648 people have browsed it

How to Efficiently Sum Column Values in Multi-Dimensional PHP Arrays?

How to Sum Columnar Values in Multi-Dimensional Arrays

In multi-dimensional arrays, summarizing values along columns is a common task. Here's how it's done, considering the challenge of dynamic associative key sets:

General-Case Solution with array_walk_recursive

Using array_walk_recursive, you can consistently summarize columns regardless of key structure:

$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 Exact Keys

From PHP 5.5 onwards, you can use array_column to efficiently summarize specific columns:

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

Total Sum for All Key Sets

If you want the aggregate sum of all inner arrays with matching keys (as in the desired output), use this approach:

$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

A more advanced approach using array_column involves identifying all unique keys and then summarizing:

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