0

Input: $a as input array and $b as formatting array

$a = Array
(
    [0] => 1
    [1] => 5
    [2] => 7
)

$b = Array
(
    [0] => 5
    [1] => 3
    [2] => 4
)


$result = Array
(
    [0] => 1,5
    [1] => 5,3
    [2] => 7,4
)

How do I merge 2 arrays to achive the result above with PHP?

heaven
  • 21
  • 5
  • 1
    I don't get what `$b` array is used for in this example. You can achieve `$result` without any impact from `$b`. Please explain further, give more detail and use more unique numbers rather than `1, 2, 3` – Huy Phạm Jul 29 '21 at 05:25

1 Answers1

0

Use the array_map function as:

<?php

$a = [1, 5, 7];

$b = [5, 3, 4];

$result = array_map(null, $a, $b); // passing null as the callback to perform a zip operation on multiple arrays

print_r($result);

?>

Alternative solution, :P

<?php

$a = [1, 5, 7];

$b = [5, 3, 4];

$result = [];

foreach($a as $k => $v) {
    $result[$k] = [$v, $b[$k]];
}

print_r($result);

?>

Output:

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

    [1] => Array
        (
            [0] => 5
            [1] => 3
        )

    [2] => Array
        (
            [0] => 7
            [1] => 4
        )

)
OMi Shah
  • 5,768
  • 3
  • 25
  • 34