function array_flop($array) {
foreach($array as $k => $v) {
$result[$v][] = $k;
}
return array_reverse($result);
}
array_flip of a key value for letter and numbers
-
28-08-2022 - |
题
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?
解决方案 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;
}
不隶属于 StackOverflow