【发布时间】:2021-04-17 02:36:33
【问题描述】:
我有 2 个数组($data_1 和 $data_2),它们有不同的值但有关系,我想合并这些数组,完全用键名
$data_1 =
'[
{
"fruit": "apple",
"weight": "15"
},
{
"fruit": "durian",
"weight": "50"
},
{
"fruit": "orange",
"weight": "10"
}
]';
$data_2 =
'[
{
"color": "red",
"thorn": "no"
},
{
"color": "green",
"thorn": "yes"
},
{
"color": "orange",
"thorn": "no"
}
]';
但我想组合这些数组,然后我有一个完整的数据是这样的:
$full_data =
'[
{
"fruit": "apple",
"weight": "15",
"color": "red",
"thorn": "no"
},
{
"fruit": "durian",
"weight": "50",
"color": "green",
"thorn": "yes"
},
{
"fruit": "orange",
"weight": "10",
"color": "orange",
"thorn": "no"
}
]';
我试过array_splice()
for ($i=0; $i < count($data_2); $i++) {
array_splice($data_1[$i], 0, 0, $data_2[$i]);
}
但它返回 '0' 和 '1' 而不是原始键名...
'[
{
"fruit": "apple",
"weight": "15",
"0": "red",
"1": "no"
},
{
"fruit": "durian",
"weight": "50",
"0": "green",
"1": "yes"
},
{
"fruit": "orange",
"weight": "10",
"0": "orange",
"1": "no"
}
]';
我想把那个 '0' 和 '1' 替换成原来的键名
【问题讨论】:
-
使用
array_merge代替array_splice并将其分配给第一个数组或新数组。
标签: php arrays laravel array-splice