【发布时间】:2018-10-30 10:40:15
【问题描述】:
我想将一个数组中的值添加到另一个数组中,当它们具有相同的 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"
}]
【问题讨论】:
-
现在出了什么问题?你还能显示当前输出吗?
-
那些 json 字符串无效,顺便说一句。
-
嘿@Jeff 我添加了更小的工作!我想澄清一下,结构不准确,可能有 20 层深,也可能是 1 层,谢谢!
-
@Jeff 我还为工作的 json 数据添加了当前输出示例。它正确复制不在子数组中的任何内容,但不适用于任何内部数组。
-
从你的例子中我开始更好地理解 - 你希望来自 arr2 的 ID 为“21”的人成为“24”的孩子,对吧?