我有一个像这样的对象(存储为 $videos)
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
我只想获取第一个元素的 ID,而不必遍历它。
如果它是一个数组,我会这样做:
$videos[0]['id']
以前是这样工作的:
$videos[0]->id
但现在我在上面显示的行中收到错误“不能使用 stdClass 类型的对象作为数组...”。可能是由于 PHP 升级。
那么如何在不循环的情况下获得第一个 ID?有可能吗?
谢谢!
最佳答案
array() 和 stdClass 对象都可以使用
current()
key()
next()
prev()
reset()
end()
功能。
所以,如果你的对象看起来像
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
那你就可以了;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
如果您出于某种原因需要 key ,您可以这样做;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
希望对你有用。 :-) 在 PHP 5.4 上,即使在超严格模式下也没有错误
2022 年更新:
在 PHP 7.4 之后,不推荐在对象上使用 current()
、end()
等函数。
在较新版本的 PHP 中,使用 ArrayIterator类:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
关于php - 获取 PHP stdObject 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474446/