Search code examples
phparraysgroupingtranspose

Transpose associative array of associative arrays to create associative array of indexed arrays


I need to restructuring my array so that the 2nd level keys are used as first level keys for grouping and the respective values should be pushed into the group's subarray as indexed elements.

This is my array:

[username] => Array
    (
        [3805120] => 5
        [3805121] => 7
    )

[login] => Array
    (
        [3805120] => 9
        [3805121] => 11
    )

I need something like this:

[3805120] => Array
    (
        [0] => 5
        [1] => 9
    )

[3805121] => Array
    (
        [0] => 7
        [1] => 11
    )

Solution

  • Pretty simple. You need a nested loop that sets the subarray's keys as the new array's keys and use the [] in order the new values will be "added" to the array with an auto increase value [0,1,...n].

    [username] => Array ( [3805120] => 5 [3805121] => 7 )

    [login] => Array ( [3805120] => 9 [3805121] => 11 )

    // $array is the original array
    $newArray = array();
    
    foreach($array as $key => $subarray){
      //key: username, login
      foreach($subarray as $j => $k){
        //j: 3805120, 3805121
        //k: 5,7,9,11
        $newArray[$j][] = $k;
        //1st round: $newArray[3805120][0] = 5, $newArray[3805121][0] = 7
        //2nd round: $newArray[3805120][1] = 9, $newArray[3805121][1] = 11 
      }
    }
    
    var_dump($newArray);
    

    Output:

    array(2) { [3805120]=> array(2) { [0]=> string(1) "5" [1]=> string(1) "9" } [3805121]=> array(2) { [0]=> string(1) "7" [1]=> string(2) "11" } }