php - Convert multidimensional array with key and value -
i have php array like:
array ( [11] => array ( [0] => foo [1] => bar [2] => hello ) [14] => array ( [0] => world [1] => love ) [22] => array ( [0] => stack [1] => overflow [2] => yep [3] => man ) )
i want result as:
array ( 'foo' => '11', 'bar' => '11', 'hello' => '11', 'world' => '14', 'love' => '14', 'stack' => '22', 'overflow' => '22', 'yep' => '22', 'man' => '22' )
tried foreach
inside foreach
still not make way. there 2 levels.
you didn't show foreach
attempt, it's simple:
foreach($array $key => $val) { foreach($val $v) { $result[$v] = $key; } }
you wrap inner foreach
in if(in_array())
if aren't guaranteed arrays. also, sub array values must unique or you'll key/value last one.
here's way:
$result = array(); foreach($array $key => $val) { $result = array_merge($result, array_combine($val, array_fill(0, count($val), $key))); }
creates result array using values of inner array keys , filling values parent array key. merge previous result.
Comments
Post a Comment