欢迎来到元素模板ys720.com,本站提供专业的织梦模板PBOOTCMS模板网站模板网站修改/网站仿站
当前位置:主页 > 程序教程 > 其他教程 >
其他教程

php 合并相同ID的数组数据

(元素模板) / 2023-11-21 15:50
如何使用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'],
        );
代码如下:
 $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'],
            ]
            ]
 
        );

Copyright @ 2013-2021 元素模板 www.ys720.com All Rights Reserved. 版权所有 元素模板 www.ys720.com