如何获取数组中特定值的键名
我有一个如下数组:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
我需要找出 $arr['firstStringName']
的索引,以便能够循环 array_keys($arr)
并按索引返回键字符串 'firstStringName'
。我怎样才能做到这一点?
I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName']
so that I am able to loop through array_keys($arr)
and return the key string 'firstStringName'
by its index. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
array_search()
是以下功能:实现这个:如果您有一个值并想要查找该键,请像这样使用
array_search()
:$key
现在将包含值'a'
的键(即'first'
)。array_search()
is the feature that accomplishes this:If you have a value and want to find the key, use
array_search()
like this:$key
will now contain the key for the value'a'
(that is,'first'
).将返回当前数组元素的键值
http://uk.php.net/manual/en/ function.key.php
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
如果我理解正确,您可以使用:
参见 PHP 手册
If I understand correctly, you can use:
See PHP manual
这是另一个选择
Here is another option
如果名称是动态的,那么您必须有类似的内容
,这意味着 $key 包含该键的值。
您可以使用 array_keys() 来获取数组的所有键,例如
会给您
If the name's dynamic, then you must have something like
which'd mean that $key contains the value of the key.
You can use
array_keys()
to get ALL the keys of an array, e.g.would give you
您可以这样循环遍历数组的键:
You can loop through the keys of the array this way:
如果需要返回具有相同值的数组元素,请使用 array_keys() 函数
if you need to return an array elements with same value, use
array_keys()
function使用 array_keys() 获取所有唯一键的数组。
请注意,具有命名键(例如
$arr
)的数组也可以通过数字索引(例如$arr[0]
)进行访问。http://php.net/manual/en/function.array-keys.php
use
array_keys()
to get an array of all the unique keys.Note that an array with named keys like your
$arr
can also be accessed with numeric indexes, like$arr[0]
.http://php.net/manual/en/function.array-keys.php
您可以使用 php 的 key 函数来获取密钥名称:
如下所示: PHP:key - Manual
you can use key function of php to get the key name:
like here : PHP:key - Manual