array(          &"/> array(          &">

Home >Backend Development >PHP Tutorial >问个PHP数组合并的有关问题~请

问个PHP数组合并的有关问题~请

WBOY
WBOYOriginal
2016-06-13 12:21:241048browse

问个PHP数组合并的问题~请高手指点

$arr1=array(<br />            "0"=>array(<br />                'id' => '2',<br />                'b' => 0,<br />                'num' => 4<br /><br />                ),<br /><br />            "1"=>array(<br />                'id' => '1',<br />                'b' => 0,<br />                'num' => 4 <br />                )<br />        );<br />        $arr2=array(<br />            "1"=>array(<br />                'id' => '3',<br />                'b' => 0,<br />                'num' => 4<br /><br />                ),<br /><br />            "2"=>array(<br />                'id' => '2',<br />                'b' => 0,<br />                'num' => 4 <br />                )<br />        );

想要合并这个两个数组,判断条件,id,b两个元素都相同的情况的NUM值相加。新数组键值重新排列0 1 2 3
求高手指点。谢谢。
------解决思路----------------------
$arr1=array(<br />            "0"=>array(<br />                'id' => '2',<br />                'b' => 0,<br />                'num' => 4<br /> <br />                ),<br /> <br />            "1"=>array(<br />                'id' => '1',<br />                'b' => 0,<br />                'num' => 4 <br />                )<br />        );<br /> $arr2=array(<br />            "1"=>array(<br />                'id' => '3',<br />                'b' => 0,<br />                'num' => 4<br /> <br />                ),<br /> <br />            "2"=>array(<br />                'id' => '2',<br />                'b' => 0,<br />                'num' => 4 <br />                )<br />        );<br />foreach($arr1 as $v) $res["$v[id]_$v[b]"] = $v;<br />foreach($arr2 as $v)<br />  if(isset($res["$v[id]_$v[b]"])) $res["$v[id]_$v[b]"]['num'] += $v['num'];<br />  else $res["$v[id]_$v[b]"] = $v;<br />print_r(array_values($res));
Array<br />(<br />    [0] => Array<br />        (<br />            [id] => 2<br />            [b] => 0<br />            [num] => 8<br />        )<br /><br />    [1] => Array<br />        (<br />            [id] => 1<br />            [b] => 0<br />            [num] => 4<br />        )<br /><br />    [2] => Array<br />        (<br />            [id] => 3<br />            [b] => 0<br />            [num] => 4<br />        )<br /><br />)<br /><br />

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