[英]PHP Adding multidimensional arrays together
我一直想知道如何将2个多维数组加在一起,我找到了类似的解决方案,但这并不是我想要的。 也许你们中的一个可以帮助我。 是的,我知道标题与其他提问的标题几乎相同,但是请相信我,我一直在寻找答案,但是找不到。
# array1
Array
(
[0] => Array
(
[0] => Product1
[1] => Description product 1
)
[1] => Array
(
[0] => Product2
[1] => Description product 2
)
[2] => Array
(
[0] => Product3
[1] => Description product 3
)
)
# array2
Array
(
[0] => Array
(
[0] => Price 1
[1] => Something product 1
)
[1] => Array
(
[0] => Price 2
[1] => Something product 2
)
[2] => Array
(
[0] => Price 3
[1] => Something product 3
)
)
#resultant array
Array
(
[0] => Array
(
[0] => Product1
[1] => Description product 1
[3] => Price 1
[4] => Something product 1
)
[1] => Array
(
[0] => Product2
[1] => Description product 2
[2] => Price 2
[3] => Something product 2
)
[2] => Array
(
[0] => Product3
[1] => Description product 3
[2] => Price 3
[3] => Something product 3
)
)
如您所见,我想将2个数组加在一起。 我看到了其他几个答案,但它们使用php函数array_merge()
的构建。 如果我使用它,将导致如下所示:
#resultant array
Array
(
[0] => Array
(
[0] => Product1
[1] => Description product 1
)
[1] => Array
(
[0] => Product2
[1] => Description product 2
)
[2] => Array
(
[0] => Product3
[1] => Description product 3
)
[3] => Array
(
[0] => Price 1
[1] => Something product 1
)
[4] => Array
(
[0] => Price 2
[1] => Something product 2
)
[5] => Array
(
[0] => Price 3
[1] => Something product 3
)
)
)
如您所见,不幸的是这不是我想要的。 我希望为我的问题找到解决方案。
感谢您阅读我的文章。
干杯科迪
您可以使用array_map
将array_merge
应用于每个子array_map
:
$result = array_map('array_merge', $array1, $array2);
有关更多信息,请参见array_map手册,尤其是示例3。
你可以这样做
$final = [];
foreach($arr1 as $key => $value){
// loop over the second array elements
foreach($arr2[$key] as $key2 => $value2){
// append the second array values to the first array
$value[] = $value2;
}
// append the new array to the final array
$final[] = $value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.