Merge values from different arrays to one with the same key

前端 未结 3 655
南笙
南笙 2020-12-12 07:38

I have two arrays:

Array
(
    [0] => 5
    [1] => 4
)
Array
(
    [0] => BMW
    [1] => Ferrari
)

And I would like to have tha

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 08:16

    You can use array_map with null as the first argument (there is an example in the manual), to get your desired result:

     5, 1 => 4];
    $cars = [0 => 'BMW', 1 => 'Ferrari'];
    
    var_export(array_map(null, $nums, $cars));
    

    Output:

    array (
    0 => 
    array (
        0 => 5,
        1 => 'BMW',
    ),
    1 => 
    array (
        0 => 4,
        1 => 'Ferrari',
    ),
    )
    

    Note that the following input would give the same result:

    $nums = ['puff' => 5, 'powder' => 4];
    $cars = ['powder' => 'BMW', 'puff' => 'Ferrari'];
    

    It is the order, not the keys, that determine the pairings in the result when using array_map as above.

    To associate by key using foreach (note order of $cars):

     5, 1 => 4];
    $cars = [1 => 'Ferrari', 0 => 'BMW'];
    foreach($nums as $k => $num)
        $result[] = [$num, $cars[$k]];
    
    var_export($result);
    

    Results also in the desired output.

提交回复
热议问题