在php数组中搜索值并获取所有键

时间:2022-09-08 21:37:39

Is there any better (= quicker ) solution to get all keys of value in array than foreach loop with if?

是否有更好的(=更快)解决方案来获取数组中的所有键值而不是使用if的foreach循环?

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r($array); will give me:

的print_r($阵列);会给我:

Array ( [0] => apple [1] => orange [2] => pear [3] => banana [4] => apple [5] => pear [6] => kiwi [7] => kiwi [8] => kiwi )

array_search("kiwi", $array); will give me 6

array_search(“kiwi”,$ array);会给我6

But I want all keys of kiwi. So I want 6,7,8. In this case.

但我想要奇异果的所有钥匙。所以我想要6,7,8。在这种情况下。

Bruteforce search loop:

暴力搜索循环:

 $searchObject = "kiwi";
 $keys = array();
 foreach($array as $k => $v) {
 if($v == $searchObject) $keys[] = $k; 
}

3 个解决方案

#1


21  

Alternatively, you could also use array_keys in this case, and providing the second parameter needle:

或者,您也可以在这种情况下使用array_keys,并提供第二个参数needle:

$array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi');
$searchObject = 'kiwi';
$keys = array_keys($array, $searchObject);
print_r($keys);

Sample Output

样本输出

#2


1  

function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r( array_search_values( 'kiwi', $array,true));

#3


-1  

Try this :)

尝试这个 :)

<?php
    $array = array('apple', 'orange', 'pear', 'banana', 'apple','pear', 'kiwi', 'kiwi', 'kiwi');
    $count = count($array);
    $str_to_search = 'kiwi';
    for($i=0;$i<$count;$i++){
        if($array[$i] == $str_to_search){
            echo $i.",";
        }
    }
?>

#1


21  

Alternatively, you could also use array_keys in this case, and providing the second parameter needle:

或者,您也可以在这种情况下使用array_keys,并提供第二个参数needle:

$array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi');
$searchObject = 'kiwi';
$keys = array_keys($array, $searchObject);
print_r($keys);

Sample Output

样本输出

#2


1  

function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r( array_search_values( 'kiwi', $array,true));

#3


-1  

Try this :)

尝试这个 :)

<?php
    $array = array('apple', 'orange', 'pear', 'banana', 'apple','pear', 'kiwi', 'kiwi', 'kiwi');
    $count = count($array);
    $str_to_search = 'kiwi';
    for($i=0;$i<$count;$i++){
        if($array[$i] == $str_to_search){
            echo $i.",";
        }
    }
?>