php二維數(shù)組相同鍵名相加實(shí)例
導(dǎo)語:在php二維數(shù)組雷同鍵名相加,你寫嗎?下面的是百分網(wǎng)小編為大家搜集的php二維數(shù)組相同鍵名相加實(shí)例,希望對(duì)你會(huì)有所幫助。
Array
(
[uid] => 19
[pid] => Array
(
[0] => 91
[1] => 81
)
[price] => Array
(
[0] => 6
[1] => 14
)
[pnum] => Array
(
[0] => 1
[1] => 1
)
)
求相同鍵名的.值相加如(price 的相加結(jié)果) 數(shù)組條數(shù)不確定
------解決方案--------------------
$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);
【php二維數(shù)組相同鍵名相加實(shí)例】相關(guān)文章:
1.java旋轉(zhuǎn)二維數(shù)組實(shí)例