Home >Backend Development >PHP Tutorial >php二维数组雷同键名相加

php二维数组雷同键名相加

WBOY
WBOYOriginal
2016-06-13 12:00:351053browse

php二维数组相同键名相加

<br />Array<br />(<br />    [uid] => 19<br />    [pid] => Array<br />        (<br />            [0] => 91<br />            [1] => 81<br />        )<br /><br />    [price] => Array<br />        (<br />            [0] => 6<br />            [1] => 14<br />        )<br /><br />    [pnum] => Array<br />        (<br />            [0] => 1<br />            [1] => 1<br />        )<br /><br />)<br />


求相同键名的值相加如(price 的相加结果) 数组条数不确定
------解决方案--------------------
$ar = Array(<br />    'uid' => 19,<br />    'pid' => Array (<br />            0 => 91,<br />            1 => 81,<br />        ),<br />    'price' => Array (<br />            0 => 6,<br />            1 => 14,<br />        ),<br />    'pnum' => Array (<br />            0 => 1,<br />            1 => 1,<br />        ),<br />);<br /><br />$r = array_map(function($t) {<br />    return is_array($t) ? array_sum($t) : $t;<br />   }, $ar);<br />print_r($r);
Array<br />(<br />    [uid] => 19<br />    [pid] => 172<br />    [price] => 20<br />    [pnum] => 2<br />)<br /><br />

------解决方案--------------------
直接用foreach也可以。
$ar = Array(<br />    'uid' => 19,<br />    'pid' => Array (<br />            0 => 91,<br />            1 => 81,<br />        ),<br />    'price' => Array (<br />            0 => 6,<br />            1 => 14,<br />        ),<br />    'pnum' => Array (<br />            0 => 1,<br />            1 => 1,<br />        ),<br />);<br />foreach($ar as $k=>$v){<br />    $arr[$k] = is_array($v) ? array_sum($v) : $v;<br />}<br />print_r($arr);

Statement:
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