0

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?

scrowler
  • 24,273
  • 9
  • 60
  • 92
tester2001
  • 1,053
  • 3
  • 14
  • 24

2 Answers2

2

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;

}
Rob Baillie
  • 3,436
  • 2
  • 20
  • 34
1
function array_flop($array) {
    foreach($array as $k => $v) {
        $result[$v][] = $k;
    }
    return array_reverse($result);
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Reposting Rob Baillie's answer in function form... His won't throw undefined index errors like yours will either. (won't -1 you, because this **is** a useful answer) – scrowler Dec 03 '13 at 20:05
  • @scrowler: Didn't "repost" anything. There was no answer displayed when I submitted. Also, care to show an example execution where there are any notices? – AbraCadaver Dec 03 '13 at 20:11
  • You're right, couldn't replicate my idea of this producing undefined index errors. I would however suggest that you should `return array_reverse($result);` to get the order the same as the QA. – scrowler Dec 03 '13 at 20:17