当前位置:Gxlcms > PHP教程 > php二维数组雷同键名相加

php二维数组雷同键名相加

时间:2021-07-01 10:21:17 帮助过:7人阅读

php二维数组相同键名相加

Array
(
[uid] => 19
[pid] => Array
(
[0] => 91
[1] => 81
)

[price] => Array
(
[0] => 6
[1] => 14
)

[pnum] => Array
(
[0] => 1
[1] => 1
)

)


求相同键名的值相加如(price 的相加结果) 数组条数不确定
------解决方案--------------------
$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
)


------解决方案--------------------
直接用foreach也可以。
$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);

人气教程排行