php二维数组雷同键名相加_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);
上一篇: 刚接触yii框架,问一个有关问题
下一篇: 神奇的没法解压之shell_exec