phparraysmultidimensional-arraytranspose

Transpose an array of objects


I have the array below:

[1]=>
  array(2) {
    [0]=>
        object(stdClass)#23 (7) {
          ["AddressesTableID"]=> string(1) "8"
          ["AccreditNo"]=> string(13) "5129876de28ff"
          ["Type"]=> string(4) "home"
          ["Street"]=> string(34) "Wallace, Village, Under the bridge"
          ["Municipality"]=> string(8) "Tortuous"
          ["Province"]=> string(8) "Sardonic"
          ["ContactNo"]=> string(8) "92012010"
        }
    [1]=>
        object(stdClass)#24 (7) {
          ["AddressesTableID"]=> string(1) "9"
          ["AccreditNo"]=> string(13) "5129876de28ff"
          ["Type"]=> string(6) "office"
          ["Street"]=> string(25) "Rasputin Query, Palpitate"
          ["Municipality"]=> string(7) "Opulent"
          ["Province"]=> string(6) "Number"
          ["ContactNo"]=> string(8) "29101011"
    }
  }

Can you guys help me on how to transform this into:

Where all the values are grouped as an array into similar keys?

["AccreditNo"]=> array(2) { "5129876de28ff", "GKIJUGUIKGI" }
["Type"]=> array(2) { "home", "home" }
["Street"]=> ...
["Municipality"]=> ... 
["Province"]=> ...
["ContactNo"]=> ...

Solution

  • Try with:

    $input  = array( /* your input data*/ );
    $output = array();
    
    foreach ( $input as $data ) {
      foreach ( $data as $key => $value ) {
        if ( !isset($output[$key]) ) {
          $output[$key] = array();
        }
        $output[$key][] = $value;
      }
    }