Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build associative array based on values of another associative array

I'm looking for an elegant way to turn this array:

Array (
  [foo] => 1
  [bar] => 1
  [zim] => 3
  [dib] => 6
  [gir] => 1
  [gaz] => 3
)

Into this array:

Array (
  [1] => Array ( foo, bar, gir ),
  [3] => Array ( zim, gaz ),
  [6] => Array ( dib )
)

Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.

Thanks!

like image 848
maček Avatar asked Dec 08 '22 03:12

maček


2 Answers

$input = array(
  'foo' => 1,
  'bar' => 1,
  'zim' => 3,
  'dib' => 6,
  'gir' => 1,
  'gaz' => 3
)

$output = array();
foreach ( $input as $k => $v ) {
  if ( !isset($output[$v]) ) {
    $output[$v] = array();
  }

  $output[$v][] = $k;
}
like image 101
hsz Avatar answered Dec 09 '22 16:12

hsz


I think this will do it just fine:

foreach ($arr1 as $k => $val) $arr2[$val][] = $k;

where $arr1 is the original array outputting the new array to $arr2.

like image 26
animuson Avatar answered Dec 09 '22 16:12

animuson