简体   繁体   中英

Merge the rows of two arrays (appending row data from one array to a row in another array)

I have two arrays populated from CodeIgniter query result sets (from calls of result_array() ) and I need to merge the rows from the two arrays respectively/synchronously.

$array1 = [
    ['name' => 'John', 'course' => 'BSIT'], 
    ['name' => 'Jane', 'course' => 'BSHRM'],
];
$array2 = [
    ['balance' => '1000', 'date' => '2013-05-01'], 
    ['balance' => '2000', 'date' => '2013-05-07'], 
];

How can I append the elements [balance], [date] from $array2 to $array1 so that the result looks like this:

[
    [
        'name' => 'John',
        'course' => 'BSIT',
        'balance' => '1000',
        'date' => '2013-05-01'
    ], 
    [
        'name' => 'Jane',
        'course' => 'BSHRM',
        'balance' => '2000',
        'date' => '2013-05-07'
    ]
]

I have tried:

for($i = 0; $i<count($array1); $i++)
{
    array_merge($array1[$i], $array2[$i]);
}

but I get an error that arguments are not array even if I do it like this:

for($i = 0; $i<count($array1); $i++)
{
    array_merge(array($array1[$i]), array($array2[$i]));
}

Try setting the array_merge equal to something:

for($i = 0; $i<count($array1); $i++)
{
    $array1[$i] = array_merge($array1[$i], $array2[$i]);
}
$merged_array = array_map(function($a, $b) {
  return array_merge($a, $b);
}, $array1, $array2));

尝试使用array_merge_recursive()函数

There is a simpler way to merge the rows of two or more arrays. Call array_map() with a callback of array_merge() and then list the arrays as final function parameters. array_map() will synchronously isolate one row at a time from the input arrays so that array_merge() can combine the two rows into one.

Code: ( Demo )

var_export(
    array_map('array_merge', $array1, $array2)
);

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