0

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.

2
  • 1
    I think you're going to have to brute-force this approach. With any luck, I am wrong about this. Commented Feb 6, 2012 at 22:04
  • try some combination of array_walk and array_flip, or check out the multi_array_flip function given in the comments at php.net/manual/en/function.array-flip.php Commented Feb 6, 2012 at 22:06

1 Answer 1

6

Here you go.

$final_array = array();
foreach($initial_array as $key => $val){
    foreach($val as $v){
        $final_array[$v][] = $key;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

the $val is an array in his $initial_array example, isn't it?
$val are the second level arrays in the $initial_array, yes.
oh when you don't specify that in foreach it will just grab the value, as we don't need those keys.. i think i get it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.