Search code examples
phparraysmultidimensional-arraymergegrouping

Merge two indexed arrays of indexed arrays based on first column value


I have two arrays like this:

$array1 = [
    [10, 'Some Name..'],
    [11, 'Some Name..'],
    [13, 'Some Name..'],
];

$array2 = [
    [13, 'Viewed']
];

How can I merge these two arrays without looping? Is there any php functionality available for this? I need this kind of output:

[
    [10, 'Some Name..'],
    [11, 'Some Name..'],
    [13, 'Some Name..', 'Viewed']
]

Solution

  • You can use the PHP function array_merge_recursive. See the example:

    <?php
    $ar1 = array("color" => array("favorite" => "red"), 5);
    $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
    $result = array_merge_recursive($ar1, $ar2);
    print_r($result);
    ?>