PHP:合并 2 个多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1558291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Merge 2 Multidimensional Arrays
提问by ticallian
I need to merge 2 multidimensional arrays together to create a new array.
The 2 arrays are created from $_POSTand $_FILESand I need them to be associated with each other.
我需要将 2 个多维数组合并在一起以创建一个新数组。
这两个数组是从$_POST和创建的$_FILES,我需要它们相互关联。
Array #1
数组#1
Array
(
[0] => Array
(
[0] => 123
[1] => "Title #1"
[2] => "Name #1"
)
[1] => Array
(
[0] => 124
[1] => "Title #2"
[2] => "Name #2"
)
)
Array #2
数组#2
Array
(
[name] => Array
(
[0] => Image001.jpg
[1] => Image002.jpg
)
)
New Array
新阵列
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"
)
)
The current code i'm using works, but only for the last item in the array.
I'm presuming by looping the array_mergefunction it wipes my new array every loop.
我正在使用的当前代码有效,但仅适用于数组中的最后一项。
我假设通过循环该array_merge函数,它会在每个循环中擦除我的新数组。
$i=0;
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray = array_merge($value,array($_FILES['Upload']['name'][$i]));
$i++;
}
How do I correct this?
我该如何纠正?
采纳答案by Jay Paroline
$i=0;
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,array($_FILES['Upload']['name'][$i]));
$i++;
}
the [] will append it to the array instead of overwriting.
[] 将它附加到数组而不是覆盖。
回答by wintondeshong
Use either of the built-in array functions:
使用任一内置数组函数:
array_merge_recursiveor array_replace_recursive
array_merge_recursive或者 array_replace_recursive
回答by Marius
Using just loops and array notation:
仅使用循环和数组符号:
$newArray = array();
$i=0;
foreach($arary1 as $value){
$newArray[$i] = $value;
$newArray[$i][] = $array2["name"][$i];
$i++;
}

