如何获得所有具有相同值的数组键 [英] How to get all array keys with same value
本文介绍了如何获得所有具有相同值的数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我几乎尝试了所有事情,通读了整个php.net,但我似乎找不到一种方法来获取具有相同值的所有键的数组。
I try pretty much everything, read trough whole php.net and I can't seem to find a way how to get array of all keys that have the same value.
例如,这是数组:
Array
(
[869] => 87
[938] => 89
[870] => 127
[871] => 127
[940] => 127
[942] => 123
[947] => 123
[949] => 75
)
在我的情况下,我们想要的数组是:
Array we want in my case is:
Array
(
[1] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[2] => array
(
[1] => 942
[2] => 947
)
)
推荐答案
这是一个可以执行您想要的功能的函数。许多不是最简单的方法,但它可以起作用:
Here is a function that will do what you want. Many not be the simplest it could be but it works:
<?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
)
)
这篇关于如何获得所有具有相同值的数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文