0

I have the following data structure $all =

[0] => stdClass Object
    (
        [[email protected]] => Array
            (
                [usr] => 130
                [fname] => Bob
                [lname] => thekid
                [email] => [email protected]
                [news] => 0
                [wres] => 1
                [SWAGLeaders] => 0
                [cca-cpg] => 1
                [cleanup-cpg] => 0
                [gas-cpg] => 1
                [pollinators-cpg] => 0
                [climate-int] => 0
                [composting-int] => 0
                [energy-int] => 1
                [other-int] => 0
                [pollinators-int] => 0
                [recycling-int] => 0
                [transport-int] => 1
                [trees-int] => 0
                [water-int] => 0
            )

    )

How do I access the inner keys/values?

I tried print_r($all[0]['[email protected]']); but that produced nothing

also, is '[email protected]' a key? or a variable? I thought it was a key whose value is the array and then inside the array we have additional key/value pairs

1 Answer 1

4

That is clearly an object (denoted by the stdClass Object in that output), not an array. You can access it with $all->{"[email protected]"}. This is how you force complex interpolation in place of a PHP symbol, where the symbol violates PHP's naming rules. So for example, object properties with dashes, or other illegal symbols, in them can be forced to be evaluated as strings and then as property names by wrapping them in strings and then in braces: $obj->{"this-is-ok"} whereas $obj->this-is-not.

As a side note, if this object comes from JSON, you can always force it to be stored as an array by utilizing the second argument of json_decode(), which if set to true will force the object to be built as an array instead. For some people this may make the dereferencing of keys easier. So if $all["[email protected]"] seems more natural to you than $all->{"[email protected]"} that might be the better approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.