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

php二维数组雷同键名相加

WBOY
Release: 2016-06-13 12:00:35
Original
1054 people have browsed it

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 />
Copy after login


求相同键名的值相加如(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);
Copy after login
Array<br />(<br />    [uid] => 19<br />    [pid] => 172<br />    [price] => 20<br />    [pnum] => 2<br />)<br /><br />
Copy after login

------解决方案--------------------
直接用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);
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template