-3

I'm currently stuck on how to merge multi query result into single result like;

multiple result:

$a1 = array(
["name" => "coca-cola"], 
["name" => "sprite"], 
["name" => "pepsi"]
);

$a2 = array(
["color" => "red"], 
["color" => "green"], 
["color" => "blue"]
);

$a3 = array(
["price" => 2], 
["price" => 1], 
["price" => 4]
);

expected output:

$res = array(
["name" => "coca-cola","color" => "red", "price" => 2],
["name" => "sprite","color" => "green", "price" => 1],
["name" => "pepsi","color" => "blue", "price" => 4]
);
  • I am going to close this page a mega-duplicate so I will not post an answer. In the meantime, you can use this: [`array_map('array_merge', $a1, $a2, $a3))`](https://3v4l.org/fF0Mr) – mickmackusa Oct 06 '22 at 04:14

2 Answers2

0

Try this solution.

$a1 = array(
    ["name" => "coca-cola"],
    ["name" => "sprite"],
    ["name" => "pepsi"]
);

$a2 = array(
    ["color" => "red"],
    ["color" => "green"],
    ["color" => "blue"]
);

$a3 = array(
    ["price" => 2],
    ["price" => 1],
    ["price" => 4]
);

$res = array();
for($i=0; $i<count($a1); $i++){
    $res[] = array_merge($a1[$i],$a2[$i],$a3[$i]);
}

Here we are assuming that all $a1, $a3, $a3 arrays have the same dimension.

Zeusarm
  • 1,038
  • 6
  • 14
0

One more solution:

$result = array_map(
    function($name, $color, $price) {
        return array_merge($name, $color, $price);
    },
    $a1, $a2, $a3
);

print_r($result);

share PHP code

Array
(
    [0] => Array
        (
            [name] => coca-cola
            [color] => red
            [price] => 2
        )

    [1] => Array
        (
            [name] => sprite
            [color] => green
            [price] => 1
        )

    [2] => Array
        (
            [name] => pepsi
            [color] => blue
            [price] => 4
        )

)
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39