php:如何从数字索引中获取关联数组键? [英] php: how to get associative array key from numeric index?

查看:30
本文介绍了php:如何从数字索引中获取关联数组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

$array = array( 'one' =>'value', 'two' => 'value2' );

如何从 $array[1] 取回字符串 one ?

how do I get the string one back from $array[1] ?

推荐答案

你没有.您的数组没有键 [1].你可以:

You don't. Your array doesn't have a key [1]. You could:

  • 创建一个包含键的新数组:

  • Make a new array, which contains the keys:

$newArray = array_keys($array);
echo $newArray[0];

但值一"位于 $newArray[0],而不是 [1].
一个快捷方式是:

But the value "one" is at $newArray[0], not [1].
A shortcut would be:

echo current(array_keys($array));

  • 获取数组的第一个键:

  • Get the first key of the array:

     reset($array);
     echo key($array);
    

  • 获取值value"对应的key:

  • Get the key corresponding to the value "value":

    echo array_search('value', $array);
    

  • 这一切都取决于您究竟想要做什么.事实是,[1] 不对应于一",无论你如何转动它.

    This all depends on what it is exactly you want to do. The fact is, [1] doesn't correspond to "one" any which way you turn it.

    这篇关于php:如何从数字索引中获取关联数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆