Search code examples
phparraysmultidimensional-arraymergearray-merge

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

Solution

  • Try setting the array_merge equal to something:

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