Merge values from different arrays to one with the same key

走远了吗. 提交于 2019-11-28 14:40:57

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"]);
FedeCaceres
<?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
        )

)

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.

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