【发布时间】:2021-11-28 20:37:15
【问题描述】:
我正在尝试合并两个多个数组。
两个数组都有相同的项({ "ort": "rom", "lioc": "inrom" })。
$test_1 = '
{
"hotels" : {
"hotel" : [
{ "ort": "rom", "lioc": "inrom" },
{ "ort": "paris", "lioc": "inpsrisd" },
{ "ort": "berlin", "lioc": "inberlin" },
{ "ort": "milano", "lioc": "inmilano" },
{ "ort": "paris", "lioc": "anotherinpsrisd" },
{ "ort": "muc", "lioc": "inmuc" }
]
}
}
';
$test_2 = '
{
"hotels" : {
"hotel" : [
{ "ort": "rom", "lioc": "inrom" },
{ "ort": "beijing", "lioc": "wanda" }
]
}
}
';
$arr_test1 = json_decode($test_1, TRUE);
$arr_test2 = json_decode($test_2, TRUE);
var_dump(json_encode(array_merge_recursive($arr_test1, $arr_test2)));
var_dump(json_encode(array_unique(array_merge($arr_test1,$arr_test2), SORT_REGULAR)));
如果我运行这段代码,我会得到以下结果。
result1:
{
"hotels" : {
"hotel" : [
{ "ort": "rom", "lioc": "inrom" },
{ "ort": "paris", "lioc": "inpsrisd" },
{ "ort": "berlin", "lioc": "inberlin" },
{ "ort": "milano", "lioc": "inmilano" },
{ "ort": "paris", "lioc": "anotherinpsrisd" },
{ "ort": "muc", "lioc": "inmuc" },
{"ort":"rom","lioc":"inrom"},
{"ort":"beijing","lioc":"wanda"}
]
}
}
result2:
{
"hotels" : {
"hotel" : [
{ "ort": "rom", "lioc": "inrom" },
{ "ort": "beijing", "lioc": "wanda" }
]
}
}
两者都不是我的预期结果。
正如您在此屏幕截图中看到的,{ "ort": "rom", "lioc": "inrom" } 项目在 result1 中重复。
关键是不知道数组的键是什么,也不知道数组的深度。
我想得到没有像这样重复项的合并数组。
{
"hotels" : {
"hotel" : [
{ "ort": "rom", "lioc": "inrom" },
{ "ort": "paris", "lioc": "inpsrisd" },
{ "ort": "berlin", "lioc": "inberlin" },
{ "ort": "milano", "lioc": "inmilano" },
{ "ort": "paris", "lioc": "anotherinpsrisd" },
{ "ort": "muc", "lioc": "inmuc" },
{ "ort": "beijing", "lioc": "wanda" }
]
}
}
我该如何解决这个问题?
【问题讨论】: