在PHP中有以下数组.Id和Total键对于相同的Id值是相同的.数组如下:在PHP中有以下数组.Id和Total键对于相同的Id值是相同的.数组如下: Array( [0] = Array ( [id] = 1 [total] = 100 [line] = books [value] = 10 ) [1] = Array ( [id] = 1 [total] = 100 [line] = cars [value] = 50 ) [2] = Array ( [id] = 1 [total] = 100 [line] = cover [value] = 30 ) [3] = Arr
Array
(
[0] => Array
(
[id] => 1
[total] => 100
[line] => books
[value] => 10
)
[1] => Array
(
[id] => 1
[total] => 100
[line] => cars
[value] => 50
)
[2] => Array
(
[id] => 1
[total] => 100
[line] => cover
[value] => 30
)
[3] => Array
(
[id] => 2
[total] => 80
[line] => books
[value] => 5
)
[4] => Array
(
[id] => 2
[total] => 80
[line] => cover
[value] => 35
)
[5] => Array
(
[id] => 2
[total] => 80
[line] => cars
[value] => 40
)
想在一个数组中合并Line和Value元素.下面是想实现的效果:
Array
(
[0] => Array
(
[id] => 1
[total] => 100
[details] => Array
(
[0] => Array
(
[line] => books
[value] => 10
)
[1] => Array
(
[line] => cars
[value] => 50
)
[2] => Array
(
[line] => cover
[value] => 30
)
)
)
)
[1] => Array
(
[id] => 2
[total] => 80
[details] => Array
(
[0] => Array
(
[line] => books
[value] => 5
)
[1] => Array
(
[line] => cars
[value] => 35
)
[2] => Array
(
[line] => cover
[value] => 40
)
)
)
)
实现代码如下:
$out=array();
foreach($array as $x){
$out[$x['id']]['id']=$x['id'];
$out[$x['id']]['total']=$x['total'];
$out[$x['id']]['details'][]=array('line'=>$x['line'],'value'=>$x['value']);
}
笔记:使用id作为out键,可以添加我们自己的,但这将工作正常.
id和total将在每个循环(每个键)上被覆盖,但这没什么大不了的
line\value递增到自己的details数组
沃梦达教程
本文标题为:PHP中合并具有相同id值的数组元素
基础教程推荐
猜你喜欢
- laravel ORM关联关系中的 with和whereHas用法 2023-03-02
- php array分组,PHP中array数组的分组排序 2022-08-01
- thinkphp3.2.3框架动态切换多数据库的方法分析 2023-03-19
- PHP命名空间简单用法示例 2022-12-01
- PHP实现Redis单据锁以及防止并发重复写入 2022-10-12
- 使用PHP开发留言板功能 2023-03-13
- 在Laravel中实现使用AJAX动态刷新部分页面 2023-03-02
- PHP获取MySQL执行sql语句的查询时间方法 2022-11-09
- PHP中的错误及其处理机制 2023-06-04
- laravel 解决多库下的DB::transaction()事务失效问题 2023-03-08