简体   繁体   English

最有效的方法来查找重复值的位置php

[英]most effective way to find positions of repeated values php

I would like to the most effective way to get the position of repeated elements element in array. 我想以最有效的方式获取数组中重复元素元素的位置。 For example, if i have: 例如,如果我有:

$example = array('a','b','c','a','a','d');

So in this case 'a' is at position 0 - 3 - 4. 所以在这种情况下,'a'位于0-3-4位置。

I know we can loop through but i think in it is ineffective. 我知道我们可以循环,但我认为它是无效的。 I would be grateful if you could show me a better way to do this. 如果你能告诉我更好的方法,我将不胜感激。

Thank you very much 非常感谢你

array_keys() with the optional search_value parameter array_keys(),带有可选的search_value参数

$example = array('a','b','c','a','a','d');

print_r(array_keys($example, "a"));

output: 输出:

Array ( [0] => 0 [1] => 3 [2] => 4 ) 

If you don't have a particular vlaue in mind and want the positions of all the values: 如果您没有特定的值,并想要所有值的位置:

$example = array('a','b','c','a','a','d');



$out=array();
foreach($example as $k=>$v){

  $out[$v][]=$k;

}
echo '<pre>';

print_r($out);

returns: 收益:

Array
(
    [a] => Array
        (
            [0] => 0
            [1] => 3
            [2] => 4
        )

    [b] => Array
        (
            [0] => 1
        )

    [c] => Array
        (
            [0] => 2
        )

    [d] => Array
        (
            [0] => 5
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM