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

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

问题描述

如果我有

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

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

推荐答案

您没有.您的数组没有键[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"相对应的键:

  • 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天全站免登陆