問題描述
我有一個看起來像這樣的對象(存儲為 $videos)
I have an object (stored as $videos) that looks like this
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
我只想獲取第一個元素的 ID,而不必遍歷它.
I want to get the ID of just that first element, without having to loop over it.
如果它是一個數組,我會這樣做:
If it were an array, I would do this:
$videos[0]['id']
它曾經是這樣工作的:
$videos[0]->id
但現在我在上面顯示的行上收到錯誤無法使用 stdClass 類型的對象作為數組...".可能是由于 PHP 升級.
But now I get an error "Cannot use object of type stdClass as array..." on the line shown above. Possibly due to a PHP upgrade.
那么如何在不循環的情況下獲得第一個 ID?可能嗎?
So how do I get to that first ID without looping? Is it possible?
謝謝!
推薦答案
更新 PHP 7.4
大括號訪問語法自 PHP 7.4 起已棄用
Curly brace access syntax is deprecated since PHP 7.4
2019 年更新
繼續討論 OOPS 的最佳實踐,@MrTrick 的答案必須是標記為正確,雖然我的回答提供了一個被黑的解決方案,但它不是最好的方法.
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
使用 {} 簡單地迭代它
Simply iterate its using {}
示例:
$videos{0}->id
這樣您的對象就不會被破壞,您可以輕松地遍歷對象.
This way your object is not destroyed and you can easily iterate through object.
對于 PHP 5.6 及以下版本使用此
For PHP 5.6 and below use this
$videos{0}['id']
這篇關于獲取 PHP stdObject 中的第一個元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!