用键作为数字访问对象PHP
我有一个看起来像这样的对象:
I have an object that looks like this:
stdClass Object
(
[page] => stdClass Object
(
[1] => stdClass Object
(
[element] => stdClass Object
(
[background_color] => stdClass Object
...
当我打印print_r($arr->page)
时:
stdClass Object
(
[1] => stdClass Object
(
[element] => stdClass Object
(
[background_color] => stdClass Object
(
但这不会显示任何内容:
But this prints nothing:
print_r($arr->page->{"1"});
这会显示错误:
print_r($arr->page->1);
解析错误:语法错误,意外的T_LNUMBER,预期的T_STRING或T_VARIABLE或'{'或'$'i
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' i
如何访问"1"元素?
How can I access the "1" element?
更新:
我也尝试过$arr->page[1]
和$arr->page["1"]
,但遇到此错误:
I've also tried $arr->page[1]
and $arr->page["1"]
but get this error:
致命错误:无法将类型为stdClass的对象用作数组中的
Fatal error: Cannot use object of type stdClass as array in
更新2:
var_dump($arr->page);
打印此:
object(stdClass)#3 (1) { [1]=>
object(stdClass)#4 (1) {
["element"]=>
object(stdClass)#5 (20) {
["background_color"]=>
object(stdClass)#6 (7) {
您不能直接访问整数类变量.最好的选择是根本不使用StdClass.
You cannot access integer class variables directly. The best option is to not use StdClass at all.
如果无法控制数据源,则可以通过$foo = (array) $foo
强制转换为数组.
If you cannot control the source of your data, you can cast to an array via $foo = (array) $foo
.
您还可以遍历元素:
foreach ($obj as $key=>$val)
或
foreach (get_object_vars($obj) as $key => $val)