初始值如下:
$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'], );代码如下:
$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);//关联数组转为索引数组 var_dump($temp);输出后的值:
$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'], ] ] );