我有一个对象(存储为$ 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?有可能吗?
谢谢!
答案 0 :(得分:65)
可以使用。访问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
如果您出于某种原因需要密钥,可以这样做;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
希望对你有用。 :-) 在PHP 5.4上没有错误,即使在超严格模式下也是如此
答案 1 :(得分:63)
更新2019
继续使用OOPS的最佳实践,@ MrTrick的回答必定是 标记为正确,虽然我的答案提供了一个黑客解决方案,但不是 最好的方法。
只需使用{}
进行迭代示例:
$videos{0}->id
通过这种方式,您的对象不会被破坏,您可以轻松地遍历对象。
对于PHP 5.6及以下版本,请使用此
$videos{0}['id']
答案 2 :(得分:15)
正确:
$videos= (Array)$videos;
$video = $videos[0];
答案 3 :(得分:12)
更容易:
$firstProp = current( (Array)$object );
答案 4 :(得分:7)
$videos->{0}->id
为我工作。
由于$ videos和{0}都是对象,因此我们必须使用$videos->{0}->id
访问ID。大括号大约需要0,因为省略大括号会产生语法错误:意外' 0'期待标识符或变量或' {'或者' $'。
我正在使用 PHP 5.4.3 。
就我而言,$videos{0}->id
和$videos{0}['id']
都不起作用并显示错误:
不能使用stdClass类型的对象作为数组。
答案 5 :(得分:5)
你可以在对象上循环并在第一个循环中断... 像
这样的东西foreach($obj as $prop) {
$first_prop = $prop;
break; // exits the foreach loop
}
答案 6 :(得分:2)
使用Php交互式shell,Php 7:
➜ ~ php -a
Interactive shell
php > $v = (object) ["toto" => "hello"];
php > var_dump($v);
object(stdClass)#1 (1) {
["toto"]=>
string(5) "hello"
}
php > echo $v{0};
PHP Warning: Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
Stack trace:
#0 {main}
thrown in php shell code on line 1
Warning: Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
Stack trace:
#0 {main}
thrown in php shell code on line 1
php > echo $v->{0};
PHP Notice: Undefined property: stdClass::$0 in php shell code on line 1
Notice: Undefined property: stdClass::$0 in php shell code on line 1
php > echo current($v);
hello
只有current
正在处理对象。
答案 7 :(得分:0)
可以进行以下操作
$rows=null;
foreach ($result as $rows) break;