Home > Software engineering >  Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in
Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in

Time:02-08

I have two arrays:

$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5];
$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.

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);

CodePudding user response:

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

CodePudding user response:

An example using foreach

<?php

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

$output = [];

foreach ($a as $key => $value) {
    $output[] = [$value,  $b[$key]];
}

print_r($output);
  •  Tags:  
  • Related