PHP将多维数组加在一起

时间:2019-01-03 15:35:44

标签: php arrays merge append

我一直想知道如何将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      
        )
)
)

很不幸,这不是我想要的。我希望找到解决问题的方法。

感谢您阅读我的帖子。

干杯科迪

2 个答案:

答案 0 :(得分:0)

您可以使用array_mergearray_map应用于每个子数组:

$result = array_map('array_merge', $array1, $array2);

有关更多信息,请查看array_map的手册,尤其是示例3。

答案 1 :(得分:0)

您可以做到

$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;
}