Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert two or more Simple Arrays to Multidimensional Array?

Given that I have these arrays:

$array1:

Array
(
    [0] => Title1
    [1] => Title2
    [2] => Title3
    [3] => Title4
...

$array2:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
...

$array3:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
...

I want to convert all the upper arrays into one Multidimensional Array that looks like this:

Array
(
    [0] => Array
        (
            [0] => Title1
            [1] => A
            [2] => 1
        )

    [1] => Array
        (
            [0] => Title2
            [1] => B
            [2] => 2
        )

    [2] => Array
        (
            [0] => Title3
            [1] => C
            [2] => 3
        )
...

I have this code that does what I want but is excessive and inefficient:

$result1 = array();
foreach($array1 as $key => $value) {
    $tmp = array($value);
    if (isset($array2[$key])) {
        $tmp[] = $array2[$key];
    }
    $result1[] = $tmp;
}

$result2 = array();
$i=0;
foreach($result1 as $value){
  $result2[$i] = $value;
  $result2[$i][] = $array3[$i];
  $i++;
}

print_r($result2);

In terms of efficiency, how can I improve my code? Can this be done all in one "foreach"? What about if I have ten or even more simple arrays? If this is the case, using my code I would have to copy down the second foreach and change the variables for each other array that comes after the first two arrays.

like image 695
Ava Barbilla Avatar asked Dec 09 '22 03:12

Ava Barbilla


2 Answers

This should work for you:

Just use array_map() to loop through all arrays at once, e.g.

$result = array_map(function($v1, $v2, $v3){
    return [$v1, $v2, $v3];
}, $array1, $array2, $array3);

Or you can use call_user_func_array(), so if you expand you only have to add the variables to the array and don't have to add the arguments in the anonymous function:

$result = call_user_func_array("array_map", [NULL, $array1, $array2, $array3]);
like image 179
Rizier123 Avatar answered Dec 10 '22 15:12

Rizier123


array_map() is the way to go but it's much easier:

$result = array_map(null, $array1, $array2, $array3);
like image 40
AbraCadaver Avatar answered Dec 10 '22 17:12

AbraCadaver