在php数组中查找特定的键 [英] Finding a specific key in an php array
问题描述
在查找数组中的正确键时遇到一些麻烦:
I have some troubles finding the right key in an array:
当我有一个数组时:$ haystack
when I have an array: $haystack
$haystack = array(0 => 'apple',
1 => 'apple',
2 => 'pear',
3 => 'apple',
4 => 'banana');
,并使用array_search函数
and is use the function array_search
$key = array_search('apple', $haystack);
该函数会将$ key的值设置为'0'($ key = 0)
the function wil set the $key value to '0' ( $key = 0 )
我需要在数组(3)中找到也是苹果的第四项的键...有谁知道一个从给定索引中搜索数组并返回值的函数?
I need to find the key of the fourth item in the array (3) which is also apple... Does anyone know a function that searches the array from a given index and returns a value?
例如:
array_search_start($needle, $haystack, $startPosition);
推荐答案
使用 array_keys
和第二个参数来指定要搜索的键的值.
Use array_keys
with the second parameter to specify value to search keys for.
$keys = array_keys($haystack, 'apple');
因此, $ keys
将包含与搜索值( apple
)相对应的找到的键的数组:
So $keys
will contain array of found keys corresponding to search value (apple
):
Array
(
[0] => 0
[1] => 1
[2] => 3
)
现在,您可以获得最后一个,或者第一个,依此类推.如果需要最后一个:
Now you can get the last one, or the first, etc. If you need the last:
$key = end($keys);
这篇关于在php数组中查找特定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!