简体   繁体   中英

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?

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

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

Using just loops and array notation:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM