4

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

vikujangid
  • 728
  • 3
  • 8
  • 19

1 Answers1

5

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).

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • @Rizier123 I got value from array with $response['abc']['@hotelId']; but it display like String(7)("asasasa") Like var_dump shows. how can i retrieve it like asasasa Only also if i try to print Like $response['abc']->{'@hotelId'}; then it show me NULL value – ankit verma Dec 23 '15 at 17:21
  • @ankitverma Then you probably stored the output from `var_dump()` in your array element. Please show your output from: `print_r($response["abc"]["@hotelld"]);` (Best just post a pastebin link here). If you really stored the output of: `var_dump()` in the element I would first search for the source where you did it and change it there, otherwise you would have to use a regex, e.g. `preg_match("/String\(\d+\)\(\"(.*?)\"\)/", $input)`. Also note that this question is actually about object properties and not array elements. – Rizier123 Dec 23 '15 at 17:26