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


猜你喜欢
- laravel通用化的CURD的实现 2023-03-17
- php微信公众号开发之秒杀 2022-11-23
- 用nohup命令实现PHP的多进程 2023-09-02
- PHP中PDO事务处理操作示例 2022-10-15
- PHP仿tp实现mvc框架基本设计思路与实现方法分析 2022-10-18
- laravel实现按月或天或小时统计mysql数据的方法 2023-02-22
- windows下9款一键快速搭建PHP本地运行环境的好工具(含php7.0环境) 2023-09-02
- PHP实现微信支付(jsapi支付)流程步骤详解 2022-10-09
- Laravel balde模板文件中判断数据为空方法 2023-08-30
- PHP简单实现二维数组的矩阵转置操作示例 2022-10-02