开发者

PHP: get a single key from object

I have an object with a single key and its value. But I don't know the key to access it. W开发者_JAVA百科hat is the most efficient way to get the key without enumerating the object?


If you just want to access the value, you don't need the key (actually property name) at all:

$value = current((array)$object);

If you really want the property name, try this:

$key = key((array)$object);


$array = array("foo" => "bar");

$keys = array_keys($array);

echo $keys[0];

// Output: foo

See: http://php.net/manual/en/function.array-keys.php


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜