I have an object that looks like this:
stdClass Object
(
[page] => stdClass Object
(
[1] => stdClass Object
(
[element] => stdClass Object
(
[background_color] => stdClass Object
...
And when I print 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"});
And this prints an error:
print_r($arr->page->1);
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' i
How can I access the "1" element?
UPDATE:
I've also tried $arr->page[1]
and $arr->page["1"]
but get this error:
Fatal error: Cannot use object of type stdClass as array in
UPDATE 2:
var_dump($arr->page);
prints this:
object(stdClass)#3 (1) { [1]=>
object(stdClass)#4 (1) {
["element"]=>
object(stdClass)#5 (20) {
["background_color"]=>
object(stdClass)#6 (7) {
Use quotes:
print_r($arr->page->{'1'});
From here: How can I access an object attribute that starts with a number?
You cannot access integer class variables directly. The best option is to not use StdClass at all.
If you cannot control the source of your data, you can cast to an array via $foo = (array) $foo
.
You can also iterate over the elements:
foreach ($obj as $key=>$val)
Or
foreach (get_object_vars($obj) as $key => $val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With