Home >Backend Development >PHP Tutorial >Addition of two-dimensional arrays with identical key names in php_PHP tutorial
Addition of php two-dimensional arrays with the same key names
Array
(
[uid] => 19
[pid] => Array
(
[0] => 91
[1] => 81
)
[price] => Array
(
[0] => 6
[1] => 14
)
[pnum] => Array
(
[0] => 1
[1] => 1
)
)
Find the addition of values with the same key name, such as (the addition result of price). The number of array items is uncertain
------Solution--------------------
$ar = Array(
'uid' => 19,
'pid' => Array (
0 => 91,
1 => 81,
),
'price' => Array (
0 => 6,
1 => 14,
),
'pnum' => Array (
0 => 1,
1 => 1,
),
);
$r = array_map(function($t) {
return is_array($t) ? array_sum($t) : $t;
}, $ar);
print_r($r);
Array
(
[uid] => 19
[pid] => 172
[price] => 20
[pnum] => 2
)
------Solution--------------------
You can also use foreach directly.
$ar = Array(
'uid' => 19,
'pid' => Array (
0 => 91,
1 => 81,
),
'price' => Array (
0 => 6,
1 => 14,
),
'pnum' => Array (
0 => 1,
1 => 1,
),
);
foreach($ar as $k=>$v){
$arr[$k] = is_array($v) ? array_sum($v) : $v;
}
print_r($arr);