Search code examples
phparraysmultidimensional-arraygroupingarray-column

How to restructure multi-dimensional array with columns as rows?


Is there an efficient way to change the structure of this multidimensional array? I want to group the column values.

//$arrayBefore
[[5, 4, 10], [11, 13, 15], [32, 14, 15]];

Desired result:

//$arrayAfter
[[5, 11, 32], [4, 13, 14], [10, 15, 15]]; 

Solution

  • You can do it based on array_column():-

    <?php
    
    $array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
    
    $final_array = [array_column($array,0),array_column($array,1),array_column($array,2)];
    
    print_r($final_array );
    

    Output:-https://eval.in/836310

    Note:- above code will work only for this array.

    More general and considering all aspects code is using foreach():-

    <?php
    $array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
    
    $final_array = array();
    
    foreach($array as $arr){
        foreach($arr as $key=>$value){
          $final_array[$key][]=$value;
        }
    }
    print_r($final_array);
    

    Output:- https://eval.in/836313