Flip two-dimensional associative array in PHP

I need to convert an array of parents to children into an array of children to parents. For example, I have an array like this:

[ 1 => [a,b,c], 2 => [b,c,d], 3 => [c,d,e], ] 

And I want to include it in this:

 [ a => [1], b => [1,2], c => [1,2,3], d => [2,3], e => [3] ] 

Is there a way to accomplish this task without using foreach nested loops? If not, what is the most efficient way to do this?

Thanks in advance!

+6
source share
3 answers

A short solution using the functions array_merge_recursive , array_combine and array_fill :

 $arr = [ 1 => ['a','b','c'], 2 => ['b','c','d'], 3 => ['c','d','e'], ]; $result = []; foreach ($arr as $k => $v) { $result = array_merge_recursive($result, array_combine($v, array_fill(0, count($v), [$k]))); } print_r($result); 

Exit:

 Array ( [a] => Array ( [0] => 1 ) [b] => Array ( [0] => 1 [1] => 2 ) [c] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [d] => Array ( [0] => 2 [1] => 3 ) [e] => Array ( [0] => 3 ) ) 
+5
source

In terms of "efficiency", I believe that a nested loop is better in this case:

 $arr = [1 => ['a','b','c'], 2 => ['b','c','d'], 3 => ['c','d','e']]; $result = []; foreach ($arr as $key => $value) { foreach ($value as $v) { $result[$v][] = $key; } } var_dump($result); 

Trying to get creative with other functions like array_map may be slower, at least according to this answer . It might be worth doing some of your own tests.

+2
source

Using closures and array_map (one can only hope that array_map is faster than the equivalent for ... loop, is it not supposed to be a native function?).

 $multimap=[ 1 => [a,b,c], 2 => [b,c,d], 3 => [c,d,e], ]; $result=[]; foreach($multimap as $k=>$arr) { $callme=function($e) use (&$result, $k) { if( ! array_key_exists ($e, $result) ) { $result[$e]=[]; } $result[$e][]=$k; return $e; // not that it matters what is returned, we're after the side-effects }; array_map($callme, $arr); } // just as yet another alternative to var_dump/print_r echo json_encode($result /*, JSON_PRETTY_PRINT */)."\n"; 
0
source

Source: https://habr.com/ru/post/1012808/


All Articles