iDaRkkO
iDaRkkO

Reputation: 3

PHP Arrays and stdClass objects

I am working on a project to get the names of an array. The arrays seem to be multidimensional, with the added bonus of being a stdclass Object. I am trying to select a key from the provided array but seem to have no luck selecting them.

echo($response->array[shoecompany]->array[1]->name);

from the information here

    stdClass Object
(
    [shoe] => shoemaker
    [shoecompany] => Array
        (
            [0] => stdClass Object
                (
                    [shoenumber] => 1
                    [name] => Blank

            [1] => stdClass Object
                (
                    [shoenumber] => 2
                    [name] => demo
                )

            [2] => stdClass Object
                (
                    [shoenumber] => certificate
                    [name] => certofsale

                )

        )

)

Nothing i do seems to pull the information i need out of this. Any ways to go about pulling, said information.

Upvotes: 0

Views: 91

Answers (2)

Sarkouille
Sarkouille

Reputation: 1232

The arrays seem to be multidimensional, with the added bonus of being a stdclass Object.

Arrays and objects aren't the same things.

I let you learn more about the specifics of both if you are curious.

Regarding access, yous use brackets - '[]' - when you want to access something in an array and an arrow - '->' - when you want to access an object's property :

$array['key'];

$object->property;

In your case, since only $response and the entries in the entry showcompany - I assume it's a typo - are objects, what you should write is :

$response->shoecompany[1]->name;

Which gives you in practical use :

foreach ($response->shoecompany as $val) {
    echo $val->shoenumber, ' : ', $val->name, '<br>'; // Or whatever you want to print, that's for the sake of providing an example
}

If it is more convenient for you to handle exclusively arrays, you can also use get_object_vars() to convert an object properties to an array :

$response = get_object_vars($response);

Upvotes: 2

Brijesh Kapletiya
Brijesh Kapletiya

Reputation: 131

Code should be like:

echo $response->shoecomapny[1]->name;

In short, to select key inside an object you need to use "->" operator and to select key inside array use "[]".

Upvotes: 1

Related Questions