PHP:从对象获取单个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3411495/
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
PHP: get a single key from object
提问by Pablo
I have an object with a single key and its value. But I don't know the key to access it. What is the most efficient way to get the key without enumerating the object?
我有一个带有单个键及其值的对象。但我不知道访问它的密钥。在不枚举对象的情况下获取密钥的最有效方法是什么?
回答by deceze
If you just want to access the value, you don't need the key (actually property name) at all:
如果您只想访问 value,则根本不需要 key (实际上是property name):
$value = current((array)$object);
If you really want the property name, try this:
如果你真的想要属性名称,试试这个:
$key = key((array)$object);
回答by thomasrutter
You can cast the object to an array like this:
您可以将对象转换为这样的数组:
$myarray = (array)$myobject;
And then, for an array that has only a single value, this should fetch the key for that value.
然后,对于只有一个值的数组,这应该获取该值的键。
$value = key($myarray);
You could do both those in one line if you like. Of course, you could also do it by enumerating the object, like you mentioned in your question.
如果你愿意,你可以在一行中完成这两项。当然,您也可以通过枚举对象来实现,就像您在问题中提到的那样。
To get the value rather than the key, then:
要获取值而不是键,则:
$value = current($myarray);
回答by gpmcadam
$array = array("foo" => "bar");
$keys = array_keys($array);
echo $keys[0];
// Output: foo