本文介绍了在php数组中搜索值并获取所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有比使用if的foreach循环更好(=更快)的解决方案来获取数组中所有值的键?
Is there any better (= quicker ) solution to get all keys of value in array than foreach loop with if?
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');
print_r($ array);会给我的:
print_r($array); will give me:
Array ( [0] => apple [1] => orange [2] => pear [3] => banana [4] => apple [5] => pear [6] => kiwi [7] => kiwi [8] => kiwi )
array_search("kiwi",$ array);会给我 6
array_search("kiwi", $array); will give me 6
但是我想要猕猴桃的所有键.所以我要 6,7,8 .在这种情况下.
But I want all keys of kiwi. So I want 6,7,8. In this case.
Bruteforce搜索循环:
Bruteforce search loop:
$searchObject = "kiwi";
$keys = array();
foreach($array as $k => $v) {
if($v == $searchObject) $keys[] = $k;
}
推荐答案
或者,您也可以使用 array_keys
,并提供第二个参数指针:
Alternatively, you could also use array_keys
in this case, and providing the second parameter needle:
$array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi');
$searchObject = 'kiwi';
$keys = array_keys($array, $searchObject);
print_r($keys);
这篇关于在php数组中搜索值并获取所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!