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

4

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?

Heterocyclic answered 13/10, 2009 at 5:10 Comment(0)
K
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.

Kele answered 13/10, 2009 at 5:19 Comment(1)
$OriginalArray already has indexed keys. Just use those in the foreach instead of manually incrementing your own counter variable.Weinberg
G
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

Gynaecomastia answered 20/11, 2012 at 22:7 Comment(1)
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.Weinberg
K
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.

Kele answered 13/10, 2009 at 5:19 Comment(1)
$OriginalArray already has indexed keys. Just use those in the foreach instead of manually incrementing your own counter variable.Weinberg
M
3

Using just loops and array notation:

$newArray = array();
$i=0;
foreach($arary1 as $value){
  $newArray[$i] = $value;
  $newArray[$i][] = $array2["name"][$i];
  $i++;
}
Modiste answered 13/10, 2009 at 5:20 Comment(0)
W
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);
Weinberg answered 16/9, 2022 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.