我尝试了很多东西,通过整个php.net阅读,我似乎找不到如何获得具有相同值的所有键的数组。
例如,这是数组:
Array
(
[869] => 87
[938] => 89
[870] => 127
[871] => 127
[940] => 127
[942] => 123
[947] => 123
[949] => 75
)
我想要的数组是:
Array
(
[1] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[2] => array
(
[1] => 942
[2] => 947
)
)
答案 0 :(得分:1)
如果您的第二个数组具有您正在检查的值,那将会更容易,例如。
Array
(
[127] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[123] => array
(
[1] => 942
[2] => 947
)
)
然后你可以这样做:
<?php
$output = array();
foreach($your_array as $key => $current) {
if( !array_key_exists($current, $output) ) {
// create new entry
$output[$current] = array( $key );
} else {
// add to existing entry
$output[$current][] = $key;
}
}
print_r($output);
?>
这应该返回上面的输出......
答案 1 :(得分:1)
这是一个可以做你想要的功能。许多不是最简单的但它有效:
<?php
$myArray = array(
869 => 87,
938 => 89,
870 => 127,
871 => 127,
940 => 127,
942 => 123,
947 => 123,
949 => 75
);
$newArray = $foundKeys = array();
$itt = 0;
foreach($myArray as $i => $x){
foreach($myArray as $j => $y ){
if($i != $j && !in_array($i,$foundKeys) && $x == $y){
if(!is_array($newArray[$itt])){
$newArray[$itt] = array($i);
}
array_push($newArray[$itt],$j);
array_push($foundKeys,$j);
}
}
$itt++;
}
print_r($newArray);
结果:
Array
(
[2] => Array
(
[0] => 870
[1] => 871
[2] => 940
)
[5] => Array
(
[0] => 942
[1] => 947
)
)
答案 2 :(得分:1)
我的简短代码。
$array =Array
(
869 => 87,
938 => 89,
870 => 127,
871 => 127,
940 => 127,
942 => 123,
947 => 123,
949 => 75
);
$return = array();
foreach ($array as $key => $value)
$return[$value][] = $key;
var_dump(array_values($return));