Join Two arrays

Viewed 70

I have two array and I want to merge those array into one array each. How can I accomplish this code and what I mistake in here:

Bellow is my code:

$intro = array( array( "name"=>"Peter","age"=>"40","location"=>"USA" ), 
            array("name"=>"Mike","age"=>"55","location"=>"USA")
);

$bikes = array( array( "brand"=>"Hero","cc"=>"150", "rpm"=>"8500"),
            array( "brand"=>"Honda","cc"=>"150", "rpm"=>"9500")
);

$result = array_merge($intro, $bikes);

print_r($result);

After merging those two arrays I am getting this result:

Array
(
    [0] => Array
        (
            [name] => Peter
            [age] => 40
            [location] => USA
        )

    [1] => Array
        (
            [name] => Mike
            [age] => 55
            [location] => USA
        )

    [2] => Array
        (
            [brand] => Hero
            [cc] => 150
            [rpm] => 8500
        )

    [3] => Array
        (
            [brand] => Honda
            [cc] => 150
            [rpm] => 9500
        )

)

But I want to get below pattern:

Array
(
    [0] => Array
        (
            [name] => Peter
            [age] => 40
            [location] => USA
            [brand] => Hero
            [cc] => 150
            [rpm] => 8500
        )
     [1] => Array
        (
            [name] => Mike
            [age] => 55
            [location] => USA
            [brand] => Yamaha
            [cc] => 150
            [rpm] => 9500
            
        )
    

)

Any help from the expert will highly appreciated.

Thanks

3 Answers

If you want them merged and lined up using the keys, you could simply use good ol' foreach:

foreach ($intro as $k => $v) {
    $result[] = array_merge($v, $bikes[$k]);
}

Or a one-liner using array_map:

$result = array_map('array_merge', $intro, $bikes);

array_map with a custom callback can help:

$intro = array( 
    array( "name"=>"Peter","age"=>"40","location"=>"USA" ), 
    array("name"=>"Mike","age"=>"55","location"=>"USA")
);

$bikes = array( 
    array( "brand"=>"Hero","cc"=>"150", "rpm"=>"8500"),
    array( "brand"=>"Honda","cc"=>"150", "rpm"=>"9500")
);

$result = array_map(function($a, $b) {
    // here you merge every subarray from 
    // `$intro` with subarray from `$bikes`
    return array_merge($a, $b);
}, $intro, $bikes);

print_r($result);

Fiddle here.

You can do this :

foreach ($intro as $k => $v) {
    $result[] = array_merge($v, $bikes[$k]);
}

result :

Array
(
[0] => Array
    (
        [name] => Peter
        [age] => 40
        [location] => USA
        [brand] => Hero
        [cc] => 150
        [rpm] => 8500
    )

[1] => Array
    (
        [name] => Mike
        [age] => 55
        [location] => USA
        [brand] => Honda
        [cc] => 150
        [rpm] => 9500
    )
)
Related