[英]PHP Adding multidimensional arrays together
I have been wondering how to add 2 multidimensional arrays together, I have found similar solutions but it is not exactly what I am trying to go for. 我一直想知道如何将2个多维数组加在一起,我找到了类似的解决方案,但这并不是我想要的。 Maybe one of you guys could help me out.
也许你们中的一个可以帮助我。 Yes I know the title is almost the same as other asked questions, but trust me, I have looked for my answer but I can't find it.
是的,我知道标题与其他提问的标题几乎相同,但是请相信我,我一直在寻找答案,但是找不到。
# 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
)
)
As you can see I would like to add the 2 arrays together. 如您所见,我想将2个数组加在一起。 I have seen several other answers but they use the build in php function
array_merge()
. 我看到了其他几个答案,但它们使用php函数
array_merge()
的构建。 If I use that it will result in something like this: 如果我使用它,将导致如下所示:
#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
)
)
)
As you can see that is not what I am looking for unfortunately. 如您所见,不幸的是这不是我想要的。 I am hoping to find a solution for my problem.
我希望为我的问题找到解决方案。
Thanks for reading my post. 感谢您阅读我的文章。
Cheers Cody 干杯科迪
You can apply array_merge
to each of your subarrays using array_map
: 您可以使用
array_map
将array_merge
应用于每个子array_map
:
$result = array_map('array_merge', $array1, $array2);
For more information check the manual for array_map , especially example 3. 有关更多信息,请参见array_map手册,尤其是示例3。
you can do this 你可以这样做
$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.