Skip to content
Advertisement

Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array

I have two arrays:

$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];

note that in $b Array ‘three’ and ‘two’ keys are not in same order as $a. also ‘six’ key is not available in $b Array.

I want this result as output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

) 

I tried to use array_map but it don’t detect keys and just zip them based of their indices:

$d = array_map(null, $a, $b);

Advertisement

Answer

Can’t you just use ksort(). Then, create a new array using `foreach’?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement