19

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
ticallian
  • 1,631
  • 7
  • 24
  • 34

4 Answers4

28

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

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
wintondeshong
  • 1,257
  • 15
  • 19
  • This vague hint of an answer is provably incorrect or needs to be explicitly demonstrated. Proof: https://3v4l.org/5Hgf8 Voters, please be careful not to ruin Stack Overflow by voting up answers that do not work. – mickmackusa Sep 16 '22 at 09:16
15
$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.

Jay Paroline
  • 2,487
  • 1
  • 22
  • 27
  • `$OriginalArray` already has indexed keys. Just use those in the `foreach` instead of manually incrementing your own counter variable. – mickmackusa Sep 16 '22 at 09:20
3

Using just loops and array notation:

$newArray = array();
$i=0;
foreach($arary1 as $value){
  $newArray[$i] = $value;
  $newArray[$i][] = $array2["name"][$i];
  $i++;
}
Marius
  • 57,995
  • 32
  • 132
  • 151
0

Modify rows by reference while you iterate. Because you have an equal number of rows and name values in your second array. Use the indexes from the first array to target the appropriate element in the second. Just push elements from the second array into the first.

Code: (Demo)

foreach ($array1 as $i => &$row) {
    $row[] = $array2['name'][$i];
}
var_export($array1);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136