How to get the items inside an Object(stdClass) in PHP?

Asked

Viewed 151 times

0

I’m importing with PHP for an api, and I don’t know how to get the values of object(stdClass) who are inside the $fotos. I tried it both ways below, but I believe I’m wrong:

foreach($fotos as $f){
var_dump($f);
}

foreach($fotos->id as $f){
var_dump($f);
}

I need to get the id, Description and 1024x1024 values

object(stdClass)#11 (3) {
    ["id"]=> string(6) "288848"
    ["description"]=> string(8) "Banheiro"
    ["1024x1024"]=> string(100) "https://s3.amazonaws.com/linkapi/images/properties/large/288848.jpeg?1587723622"
}

Update: So it worked for id and Description, but the 1024x1024 gives error, think q for being number:

foreach($fotos as $f){
            foreach($f as $foto){
                var_dump($foto->description);
            }
        }

1 answer

3

To stdClass just use:

$foo->{'1024x1024'}

Example:

<?php
$obj = (object) array('1024x1024' => 'foo');

var_dump($obj->{'1024x1024'});

Online example: https://repl.it/@inphinit/stdclass-php

It can also be written inside strings generated from double quotes (Double quoted), example:

<?php

$obj = (object) [
    'foo' => 'Valor de bar',
    'foo-bar' => 'Valor de foo-bar',
    '123-456' => 'Valor de 123-456',
    '123x456' => 'Valor de 123x456',
    '0a' => 'Valor de 0a'
];

echo "
{$obj->foo}
{$obj->{'foo-bar'}}
{$obj->{'123-456'}}
{$obj->{'123x456'}}
{$obj->{'0a'}}
";

Or using the syntax Heredoc:

echo <<<EOT
{$obj->foo}
{$obj->{'foo-bar'}}
{$obj->{'123-456'}}
{$obj->{'123x456'}}
{$obj->{'0a'}}
EOT;

Example online at IDEONE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.