Question

I have an array like this

array(123=>'c', 125=>'b', 139=>'a', 124=>'c', 135=>'c', 159=>'b');

and I want to flip the key/values so that duplicate values become an index for an array.

array(
    'a'=>array(139),
    'b'=>array(125, 159),
    'c'=>array(123, 124, 135)
);

However, array_flip seems to overwrite the keys and array_chunk only splits it based on number values.

Any suggestions?

Was it helpful?

Solution 2

function array_flop($array) {
    foreach($array as $k => $v) {
        $result[$v][] = $k;
    }
    return array_reverse($result);
}

OTHER TIPS

I think it's going to need you to loop over the array manually. It really shouldn't be hard though...

$flippedArray = array();

foreach( $arrayToFlip as $key => $value ) {

  if ( !array_key_exists( $value, $flippedArray ) {
    $flippedArray[ $value ] = array();
  }
  $flippedArray[ $value ][] = $key;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top