合并 2 JSON 个数组(压缩效果)
Merge 2 JSON arrays (Zip effect)
我不是阵法高手!我正在尝试合并 2 个相互关联的 JSON 数组。本质上,值 A 和 E 存在于 1 个数组中,而它们的索引(0、1、2 等)存在于另一个数组中。
这些是我的 2 JSONS...
的示例
JSON1:
"d": [{"A": 0,"B": "foo1","C": "bar1","D": "real1","E": 0},
{"A": 1,"B": "foo2","C": "bar2","D": "real2""E": 1},
{"A": 2,"B": "foo3","C": "bar3","D": "real3","E": 2} ]
JSON 2:
"A": ["this1","this2","this3"]
"E": ["last1","last2","last3"]
如何使用 PHP 加入,使完成的版本看起来像:
"d": [{"A": "this1","B": "foo1","C": "bar1","D": "real1","E": "last1"},
{"A": "this2","B": "foo2","C": "bar2","D": "real2","E": "last2"},
{"A": "this3","B": "foo3","C": "bar3","D": "real3","E": "last3"}]
将JSON解码为数组后,可以循环遍历第一个数组,检查第二个数组中是否存在数组键,如果存在,则将值替换为对应的值第二个数组中的数组:
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
foreach ($array1['d'] as &$arr) {
foreach ($arr as $key => &$value) {
if (array_key_exists($key, $array2)) {
$value = $array2[$key][$value];
}
}
}
echo json_encode($array1);
输出:
{
"d": [
{
"A": "this1",
"B": "foo1",
"C": "bar1",
"D": "real1",
"E": "last1"
},
{
"A": "this2",
"B": "foo2",
"C": "bar2",
"D": "real2",
"E": "last2"
},
{
"A": "this3",
"B": "foo3",
"C": "bar3",
"D": "real3",
"E": "last3"
}
]
}
我不是阵法高手!我正在尝试合并 2 个相互关联的 JSON 数组。本质上,值 A 和 E 存在于 1 个数组中,而它们的索引(0、1、2 等)存在于另一个数组中。 这些是我的 2 JSONS...
的示例JSON1:
"d": [{"A": 0,"B": "foo1","C": "bar1","D": "real1","E": 0},
{"A": 1,"B": "foo2","C": "bar2","D": "real2""E": 1},
{"A": 2,"B": "foo3","C": "bar3","D": "real3","E": 2} ]
JSON 2:
"A": ["this1","this2","this3"]
"E": ["last1","last2","last3"]
如何使用 PHP 加入,使完成的版本看起来像:
"d": [{"A": "this1","B": "foo1","C": "bar1","D": "real1","E": "last1"},
{"A": "this2","B": "foo2","C": "bar2","D": "real2","E": "last2"},
{"A": "this3","B": "foo3","C": "bar3","D": "real3","E": "last3"}]
将JSON解码为数组后,可以循环遍历第一个数组,检查第二个数组中是否存在数组键,如果存在,则将值替换为对应的值第二个数组中的数组:
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
foreach ($array1['d'] as &$arr) {
foreach ($arr as $key => &$value) {
if (array_key_exists($key, $array2)) {
$value = $array2[$key][$value];
}
}
}
echo json_encode($array1);
输出:
{
"d": [
{
"A": "this1",
"B": "foo1",
"C": "bar1",
"D": "real1",
"E": "last1"
},
{
"A": "this2",
"B": "foo2",
"C": "bar2",
"D": "real2",
"E": "last2"
},
{
"A": "this3",
"B": "foo3",
"C": "bar3",
"D": "real3",
"E": "last3"
}
]
}