Home > Backend Development > PHP Tutorial > PHP multidimensional array value accumulation function with the same key

PHP multidimensional array value accumulation function with the same key

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-29 09:10:14
Original
2151 people have browsed it

Function

<code>function array_value_sum()
{
    $res = array();
    foreach (func_get_args() as $arr) {
        foreach ($arr as $k => $v){
            if (!isset($res[$k])){
                $res[$k] = $v;
            }else{
                $res[$k] += $v;
            }
        }
    }
    return $res;
}</code>
Copy after login

Instance:

<code>$arr1 = array(311=>1, 312=>2, 314=>2);
$arr2 = array(311=>2, 312=>2, 313=>5, 314=>9);
$arr3 = array(314=>10);
$newArr = array_value_sum($arr1, $arr2, $arr3);
print_r($newArr);</code>
Copy after login

Output:

<code>Array ( [311] => 3 [312] => 4 [314] => 21 [313] => 5 )</code>
Copy after login

The above introduces the value accumulation function of the same key in PHP multi-dimensional array, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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 Issues
How to create an array within an array?
From 1970-01-01 08:00:00
0
0
0
php array
From 1970-01-01 08:00:00
0
0
0
Array to array
From 1970-01-01 08:00:00
0
0
0
php array rotation
From 1970-01-01 08:00:00
0
0
0
array
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template