我现在正为合并这两个数组而挣扎。有人能帮我用什么吗?
Array
(
[1] => Array
(
[0] => 1-1
[1] => 1-2
[2] => 1-1
[3] => 1-2
[4] => 1-1
)
[3] => Array
(
[0] => 3-3
[1] => 3-3
[2] => 3-4
[3] => 3-4
[4] => 3-3
)
)
Array[1] key [0] => 1-1 needs to combine with
Array[3] key [0] => 3-3
Array[1] key [1] => 1-2 needs to combine with
Array[3] key [1] => 3-3结果是: 1-1,3-3和1-2,3-3
请注意,第一个数组1和3中的键可以是动态的。
我做了这个:
print_r(array_merge_recursive($optionWithValue[1], $optionWithValue[3]));但是现在我有了硬编码的1和3,它们可以改变,最后我得到了:
Array
(
[0] => 1-1
[1] => 1-2
[2] => 1-1
[3] => 1-2
[4] => 1-1
[5] => 3-3
[6] => 3-3
[7] => 3-4
[8] => 3-4
[9] => 3-3
)所以这也不是我需要的
发布于 2018-12-28 15:35:38
如果数组中的数组的键相同,则可以使用reduce
$arrays = [
[
"1-1",
"1-2",
"1-1",
"1-2",
"1-1",
],
[
"3-3",
"3-3",
"3-4",
"3-4",
"3-3",
],
];
$first = array_shift($arrays);
$res = array_reduce($arrays, function($carry, $item){
foreach($item as $key => $value) {
$carry[$key] = $carry[$key] . "," . $value;
}
return $carry;
}, $first);
print_r($res);结果
Array
(
[0] => 1-1,3-3
[1] => 1-2,3-3
[2] => 1-1,3-4
[3] => 1-2,3-4
[4] => 1-1,3-3
)https://stackoverflow.com/questions/53960555
复制相似问题