PHP:合并 2 个多维数组

2022-08-30 20:47:19

我需要将2个多维数组合并在一起以创建一个新数组。
这 2 个数组是从 和 创建的,我需要它们相互关联。$_POST$_FILES

阵列 #1

Array 
(
    [0] => Array
        (
            [0] => 123  
            [1] => "Title #1"
            [2] => "Name #1"
        )
    [1] => Array
        (
            [0] => 124  
            [1] => "Title #2"
            [2] => "Name #2"
        )
)

阵列 #2

Array
(
    [name] => Array
        (
            [0] => Image001.jpg
            [1] => Image002.jpg
        )
)

新建阵列

Array
(
    [0] => Array
        (
            [0] => 123  
            [1] => "Title #1"
            [2] => "Name #1"
            [3] => "Image001.jpg"
        )
    [1] => Array
        (
            [0] => 124  
            [1] => "Title #2"
            [2] => "Name #2"
            [3] => "Image002.jpg"
        )
)

我正在使用的当前代码有效,但仅适用于数组中的最后一项。
我假设通过循环函数,它每个循环都会擦除我的新数组。array_merge

$i=0;
$NewArray = array();
foreach($OriginalArray as $value) {
    $NewArray = array_merge($value,array($_FILES['Upload']['name'][$i]));
    $i++;
}

如何更正此问题?


答案 1

使用内置数组函数之一:

array_merge_recursivearray_replace_recursive

http://php.net/manual/en/function.array-merge-recursive.php


答案 2
$i=0;
$NewArray = array();
foreach($OriginalArray as $value) {
    $NewArray[] = array_merge($value,array($_FILES['Upload']['name'][$i]));
    $i++;
}

[] 会将其附加到数组中,而不是覆盖。


推荐