how to merge data array of to array in php

Viewed 33

how to merge data array of to array in php?

i have 2 arrays like:

$a=[1,2]; $b =[3,4];

and i want to merge data like:

$data = [[1,3]],[2,4]];

how to code in php like array_merge or something in php or laravel?

i have try using array_merge but not my expectation data like this:

$data = array_merge($a, $b);

but data always return

[1,2,3,4]

i have clue about this, can someone help this problem?

1 Answers

Since we concluded in the comments that you actually want a multidimensional array, we need to create new arrays so we can swap the values around between the original arrays.

Here's one possible solution (the comments explain the different parts)

$a = [1,2];
$b = [3,4];

// Initiate a new array
$newArray = [];

// Iterate through one of the arrays
foreach ($a as $index => $value) {
    // On each iteration, take the values from both arrays for that specific array index
    // and add them as a new sub array.
    $newArray[] = [
        $a[$index],
        $b[$index]
    ];
}

$newArray will now contain a multidimensional array:

[[1,3],[2,4]]

Here's a demo: https://3v4l.org/okHhQ

Related