Merge values from different arrays to one with the same key

限于喜欢 提交于 2019-11-27 09:03:34

问题


I have two arrays:

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

And I would like to have that result. Merge the values with the same key

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

How could I do that? Is there any native PHP function that does this? I tried array_merge_recursive and array_merge but did not get the expected result


回答1:


As to @splash58 comment:

You can use array-map. Here an example:

$array = [["5", "4"], ["BMW", "Ferrari"]];
$res = array_map(null, ...$array);

Now res will contain:

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

If the array in 2 different var you can use:

$res= array_map(null, ["5", "4"], ["BMW", "Ferrari"]);



回答2:


<?php
$a = array();
$a[0] = '5';
$a[1] = '4';

$b = array();
$b[0] = 'BMW';
$b[1] = 'Ferrari';

merge_by_key($a, $b);

function merge_by_key($a, $b){
    $c = array();
    fill_array($c,$a);
    fill_array($c,$b);
    print_r($c);
}

function fill_array(&$c, $a) {
    foreach ($a as $key => $value){
        if(isset($c[$key])) {
            array_push($c[$key], $value);
        } else {
            $c[$key] = array($value);
        }
    }
}

Output:

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

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

)



回答3:


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

<?php

$nums = [0 => 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):

<?php
$nums = [0 => 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.



来源:https://stackoverflow.com/questions/54098206/merge-values-from-different-arrays-to-one-with-the-same-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!