Search code examples
phpmultidimensional-arraymergeappendarray-push

Push elements from one array into rows of another array (one element per row)


I need to push elements from one array into respective rows of another array.

The 2 arrays are created from $_POST and $_FILES and I need them to be associated with each other based on their indexes.

$array1 = [
    [123, "Title #1", "Name #1"],
    [124, "Title #2", "Name #2"],
];

$array2 = [
    'name' => ['Image001.jpg', '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?


Solution

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