首页  >  文章  >  后端开发  >  php数组整合

php数组整合

WBOY
WBOY原创
2016-06-06 20:25:181146浏览

<code class="php"> $arr=[
     ['id'=>1,'name'=>'php','num'=>3],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>1,'name'=>'php','num'=>2],
     ['id'=>3,'name'=>'python','num'=>2],
 ];
//怎么对id相同的对num求和并去重,返回的结果为
 $arr=[
     ['id'=>1,'name'=>'php','num'=>5],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>3,'name'=>'python','num'=>2],
 ];</code>

回复内容:

<code class="php"> $arr=[
     ['id'=>1,'name'=>'php','num'=>3],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>1,'name'=>'php','num'=>2],
     ['id'=>3,'name'=>'python','num'=>2],
 ];
//怎么对id相同的对num求和并去重,返回的结果为
 $arr=[
     ['id'=>1,'name'=>'php','num'=>5],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>3,'name'=>'python','num'=>2],
 ];</code>

<code>$result = [];
foreach ($arr as $v) {
    if (isset($result[$v['id']])) {
        $result[$v['id']]['num'] += $v['num'];
    }
    else {
        $result[$v['id']] = $v;
    }
}
print_r($result);</code>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn