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?

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This vague hint of an answer is provably incorrect or needs to be explicitly demonstrated. Proof: 3v4l.org/5Hgf8 Voters, please be careful not to ruin Stack Overflow by voting up answers that do not work.
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.

1 Comment

$OriginalArray already has indexed keys. Just use those in the foreach instead of manually incrementing your own counter variable.
3

Using just loops and array notation:

$newArray = array();
$i=0;
foreach($arary1 as $value){
  $newArray[$i] = $value;
  $newArray[$i][] = $array2["name"][$i];
  $i++;
}

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.