0

I have a 2d array, say:

$array = array(
         array(1, 2),
         array(3, 4),
         array(5, 6)
);

That's not symmetrical.

Is there a PHP function I can use that would make it into:

$array = array(
         array(1, 3, 5),
         array(2, 4, 6)
);

Essentially to make its rows become columns and vice versa?

I am aware it can be done via 2 foreach's, but I am just wondering if there's an quicker and "cheaper" way.

Thank you in advance

Kostas
  • 1
  • 3

1 Answers1

1

IT is possible to do using built in array_map function. You can see the code below for reference

// Input array
    $array = array(
        array(1, 2),
        array(3, 4),
        array(5, 6)
    );

    // Transpose the array
    $transposedArray = array_map(null, ...$array);

    // Output array
    $outputArray = array_map(static function ($row) {
        return array_values($row);
    }, $transposedArray);

    // Print the output array
    echo '<pre>';
    print_r($outputArray);
    exit;


//output
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
        )

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

)
Ariful Islam
  • 696
  • 6
  • 11