user975044
user975044

Reputation: 385

How can I flip an array when each value is also an array?

How would I go about flipping an array and establishing relationships between all the values and keys? For example:

I am trying to turn this:

Array ( 
[11913] => Array ( 
            [0] => 4242 
            [1] => 3981 
    ) 
[9878] => Array ( 
            [0] => 2901 
            [1] => 3981 
    ) 
[11506] => Array ( 
            [0] => 3981 
            [1] => 2901 
    ) 
 )

Into this:

Array ( 
    [3981] => Array ( 
            [0] => 11506 
            [1] => 9878 
            [2] => 11913 
        ) 
    [2901] => Array ( 
            [0] => 11506 
            [1] => 9878 
        ) 
    [4242] => Array ( 
            [0] => 11913 
        ) 
     )

Are there any PHP functions that will already do this automatically? If not what would be a way of going about this? Can't seem to wrap my head around it.

Upvotes: 0

Views: 97

Answers (1)

Grexis
Grexis

Reputation: 1512

Here you go.

$final_array = array();
foreach($initial_array as $key => $val){
    foreach($val as $v){
        $final_array[$v][] = $key;
    }
}

Upvotes: 6

Related Questions