0

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

dWinder
  • 11,597
  • 3
  • 24
  • 39
Bruno Andrade
  • 565
  • 1
  • 3
  • 17

3 Answers3

3

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"]);
dWinder
  • 11,597
  • 3
  • 24
  • 39
0
<?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
        )

)
Progrock
  • 7,373
  • 1
  • 19
  • 25
FedeCaceres
  • 158
  • 1
  • 11
0

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.

Progrock
  • 7,373
  • 1
  • 19
  • 25