如何获取数组中某个键的位置
好的,所以我需要获取该数组中“blah”的位置(位置并不总是相同)。例如:
$array = (
'a' => $some_content,
'b' => $more_content,
'c' => array($content),
'blah' => array($stuff),
'd' => $info,
'e' => $more_info,
);
所以,我希望能够返回“blah”键在数组中所在位置的编号。在这种情况下,它应该返回 3。我怎样才能快速做到这一点?并且完全不影响 $array 数组。
Ok, so I need to grab the position of 'blah' within this array (position will not always be the same). For example:
$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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您知道该密钥存在:
PHP 5.4 (演示):
PHP 5.3:
如果您不知道知道密钥存在,您可以使用
isset
检查:这与
array_search
类似,但使用任何数组中已存在的映射。我不能说它是否真的比 array_search 更好,这可能取决于场景,所以只是另一种选择。If you know the key exists:
PHP 5.4 (Demo):
PHP 5.3:
If you don't know the key exists, you can check with
isset
:This is merely like
array_search
but makes use of the map that exists already inside any array. I can't say if it's really better thanarray_search
, this might depend on the scenario, so just another alternative.$keys=array_keys($array);
将为您提供一个包含$array
的键的数组,因此,
array_search('blah', $keys);< /code> 将为您提供
$keys
中的blah
索引,因此,$array
$keys=array_keys($array);
will give you an array containing the keys of$array
So,
array_search('blah', $keys);
will give you the index ofblah
in$keys
and therefore,$array
用户
array_search
(doc)。即,`$index = array_search('blah', $array)User
array_search
(doc). Namely, `$index = array_search('blah', $array)