php循环出的id相同,在PHP中使用相同的ID组合两个多维数组

我想将一个数组中的值添加到另一个数组中,当它们具有相同的ID时,这两个数组都可能是多维的。很难解释,所以我添加了示例。

arr1=>新结构,无完整数据

arr2=>旧结构,包含完整数据

如果您想帮忙,请举例:

// arr1 (the correct structure/order, without the full data)

[{

"id": "24",

"children": [{

"id": "21",

"children": [{

"id": "15"

}]

}]

}]

// arr2 (full data, not in any specific order, may be nested)

[{

"id": "24",

"name": " x",

"time": "0",

"status": "0"

}, {

"id": "21",

"children": [{

"id": "15",

"name": "x",

"time": "0",

"status": "0"

}],

"name": "x",

"time": "0",

"status": "0"

}]

// arr3 (desired output for this example)

[{

"id": "24",

"children": [{

"id": "21",

"children": [{

"id": "15",

"name": "x",

"time": "0",

"status": "0"

}],

"name": "x",

"time": "0",

"status": "0"

}],

"name": " x",

"time": "0",

"status": "0"

}]

我试过这个:

function merge($arr1, $arr2) {

foreach($arr1 as $key => $value){

foreach($arr2 as $value2) {

if($value['id'] === $value2['id']){

$arr1[$key]['name'] = $value2['name'];

$arr1[$key]['time'] = $value2['time'];

$arr1[$key]['status'] = $value2['status'];

if (is_array($value)) {

$arr1[$key]['children'] = merge($arr1, $arr2);

}

}

}

}

return $arr1;

}

把它们组合起来,但我不知道如何正确地处理嵌套。我尝试过很多其他的方法,比如使用array_merge_recursive(),但是它不起作用,因为我想基于id值进行合并。如果能帮我走上正轨,那就太好了,谢谢。

电流输出,例如:

[{

"id": "24",

"children": [{

"id": "21",

"children": [{

"id": "15"

}]

}],

"name": " x",

"time": "0",

"status": "0"

}]

期望输出,例如:

[{

"id": "24",

"children": [{

"id": "21",

"children": [{

"id": "15",

"name": "x",

"time": "0",

"status": "0"

}],

"name": "x",

"time": "0",

"status": "0"

}],

"name": " x",

"time": "0",

"status": "0"

}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值