php 如何获取数组中键的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7459818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:43:23  来源:igfitidea点击:

How to get the position of a key within an array

phparraysarray-key

提问by SoLoGHoST

Ok, so I need to grab the position of 'blah' within this array (position will not always be the same). For example:

好的,所以我需要在这个数组中获取 'blah' 的位置(位置并不总是相同的)。例如:

$array = (
    'a' => $some_content,
    'b' => $more_content,
    'c' => array($content),
    'blah' => array($stuff),
    'd' => $info,
    'e' => $more_info,
);

So, I would like to be able to return the number of where the 'blah' key is located at within the array. In this scenario, it should return 3. How can I do this quickly? And without affecting the $array array at all.

所以,我希望能够返回数组中“blah”键所在位置的数量。在这种情况下,它应该返回 3。我怎样才能快速做到这一点?并且根本不影响 $array 数组。

回答by zerkms

$i = array_search('blah', array_keys($array));

回答by hakre

If you know the key exists:

如果您知道密钥存在:

PHP 5.4 (Demo):

PHP 5.4(演示):

echo array_flip(array_keys($array))['blah'];

PHP 5.3:

PHP 5.3:

$keys = array_flip(array_keys($array));
echo $keys['blah'];

If you don't know the key exists, you can check with isset:

如果您不知道密钥存在,您可以检查isset

$keys = array_flip(array_keys($array));
echo isset($keys['blah']) ? $keys['blah'] : 'not found' ;

This is merely like array_searchbut makes use of the map that exists already inside any array. I can't say if it's really better than array_search, this might depend on the scenario, so just another alternative.

这只不过array_search是利用了已经存在于任何数组中的映射。我不能说它是否真的比 更好array_search,这可能取决于场景,所以只是另一种选择。

回答by Pranav Hosangadi

$keys=array_keys($array);will give you an array containing the keys of $array

$keys=array_keys($array);会给你一个包含键的数组 $array

So, array_search('blah', $keys);will give you the index of blahin $keysand therefore, $array

所以,array_search('blah', $keys);会给你blahin的索引,$keys因此,$array

回答by Sajid

User array_search(doc). Namely, `$index = array_search('blah', $array)

用户array_search文档)。即,`$index = array_search('blah', $array)