phparraysmultidimensional-arraymergemapping

Merge row data from multiple arrays by first level indexes


I have two arrays as shown below. I need to merge the content of the arrays so that I can get the structure as shown in the third array at last. I have checked array_merge but can't figure out the way this is possible. Any help appreciated. Thanks.

[
    ['gross_value' => '100', 'quantity' => '1'],
    ['gross_value' => '200', 'quantity' => '1']
]

and

[
    ['item_title_id' => '1', 'order_id' => '4'],
    ['item_title_id' => '2', 'order_id' => '4']
];

I should get a merged array like this:

[
    [
        'gross_value' => '100',
        'quantity' => '1',
        'item_title_id' => '1',
        'order_id' => 4
    ],
    [
        'gross_value' => '200',
        'quantity' => '1',
        'item_title_id' => '2',
        'order_id' => 4
    ]
]

Solution

  • Use array_merge_recursive :

    Convert all numeric key to strings, (make is associative array)

    $result = array_merge_recursive($ar1, $ar2);
    print_r($result);
    

    See live demo here