欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php数组整合

程序员文章站 2022-05-08 16:38:44
...
 $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],
 ];

回复内容:

 $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],
 ];

$result = [];
foreach ($arr as $v) {
    if (isset($result[$v['id']])) {
        $result[$v['id']]['num'] += $v['num'];
    }
    else {
        $result[$v['id']] = $v;
    }
}
print_r($result);
相关标签: php