Search code examples
phparraysarray-keyarrayobject

How to access $array[@key] value


I am working with expedia API's and its working well but I don't know how to access this special type of array key. Response is given below

$response = 
stdClass Object
(
    [@size] => 1
    [@activePropertyCount] => 144
    [city] => 1
    [@hotelId] => 12345
    [HotelSummary] => stdClass Object
        (
            [@order] => 0
            [@ubsScore] => 1074874
            [hotelId] => 151689
            [RoomRateDetailsList] => stdClass Object
                (
                    [RoomRateDetails] => stdClass Object
                        (
                            [roomTypeCode] => 195577
                            [rateCode] => 202369379
                            [maxRoomOccupancy] => 3
                            [quotedRoomOccupancy] => 2
                            [minGuestAge] => 0
                            [roomDescription] => Deluxe Room
                            [propertyAvailable] => 1
                            [propertyRestricted] => 
                            [expediaPropertyId] => 526332
                        )
                )
        )
)

I want to access the value of @hotelId under the 'city' key but I can't

I tried with both type but failed both time as

$response->hotelId
and 
$response->@hotelId

Please help me.. thank you in advance


Solution

  • This should work for you:

    (This is because you can't access a property which doesn't have a legal variable name, so you have to use curly syntax)

    echo $response->{"@hotelId"};
    

    You can read more about this in the manual: http://php.net/manual/en/language.variables.variable.php

    And a quote from there:

    Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).