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 ) )
source share