Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Merge 2 Multidimensional Arrays

I need to merge 2 multidimensional arrays together to create a new array.
The 2 arrays are created from $_POST and $_FILES and I need them to be associated with each other.

Array #1

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

Array #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_merge function it wipes my new array every loop.

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

How do I correct this?

like image 680
ticallian Avatar asked Oct 13 '09 05:10

ticallian


2 Answers

Use either of the built-in array functions:

array_merge_recursive or array_replace_recursive

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

like image 197
wintondeshong Avatar answered Oct 01 '22 08:10

wintondeshong


$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.

like image 35
Jay Paroline Avatar answered Oct 01 '22 09:10

Jay Paroline