php怎么合并id相同的数组

php根据字段合并数组,根据相同的id合并数组,需求是用户有多个昵称,查出来每个昵称对应一条记录,想把同一个用户的昵称等信息合并成一条,初始数据如下: $a = array( ['id' = 1, 'name' = 'liming' ,'nickname'= 'aaa'], ['id' = 1, 'name' = 'liming' ,'nickname'= '

php根据字段合并数组,根据相同的id合并数组,需求是用户有多个昵称,查出来每个昵称对应一条记录,想把同一个用户的昵称等信息合并成一条,初始数据如下:
$a = array(
            ['id' => 1, 'name' => 'liming' ,'nickname'=> 'aaa'],
            ['id' => 1, 'name' => 'liming' ,'nickname'=> 'bbb'],
            ['id' => 1, 'name' => 'liming' ,'nickname'=> 'ccc'],
            ['id' => 2, 'name' => 'xiaoqiang' ,'nickname'=> 'ddd'],
            ['id' => 2, 'name' => 'xiaoqiang' ,'nickname'=> 'eee'],
            ['id' => 2, 'name' => 'xiaoqiang' ,'nickname'=> 'fff'],
        );
想要实现的格式:
$b = array(
            [
                'id' => 1,
                'name' => 'liming',
                'nickname_list'=> [
                ['nickname'=> 'aaa'],
                ['nickname'=> 'bbb'],
                ['nickname'=> 'ccc'],
                ]
            ],
            [
                'id' => 1,
                'name' => 'xiaoqiang',
                'nickname_list'=> [
                ['nickname'=> 'ddd'],
                ['nickname'=> 'eee'],
                ['nickname'=> 'fff'],
            ]
            ]
 
        );
实现代码如下:
 $temp = [];
        foreach ($a as $k => $value) {
            $temp[$value['id']] = ['id' => $value['id'], 'name' => $value['name']];
            $temp[$value['id']]['nickname_list'][] = $value;
        }
        $temp = array_values($temp);//关联数组转为索引数组 topstudy.com.cn
        var_dump($temp);
 

本文标题为:php怎么合并id相同的数组

基础教程推荐