Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Two arrays [duplicate]

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

like image 813
Mirza Twhidul Imran Avatar asked May 16 '26 19:05

Mirza Twhidul Imran


2 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);
like image 72
Kevin Avatar answered May 18 '26 08:05

Kevin


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.

like image 25
u_mulder Avatar answered May 18 '26 09:05

u_mulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!