Search code examples
phparraysmultidimensional-arraytranspose

Transpose a 2d array


$cnt[0] => Array(
    [0] => 0
    [1] => 0
    [2] => 0
),
$cnt[1] => Array(
    [0] => 1
    [1] => 0
    [2] => 0
)

I want convert this array to below result,

$cnt[0] = (0,0);
$cnt[1] = (0,0);
$cnt[2] = (0,1);

any php function there to convert like this format.


Solution

  • function flip($arr)
    {
        $out = array();
    
        foreach ($arr as $key => $subarr)
        {
                foreach ($subarr as $subkey => $subvalue)
                {
                     $out[$subkey][$key] = $subvalue;
                }
        }
    
        return $out;
    }
    

    see more example in PHP - how to flip the rows and columns of a 2D array