4th Avenue 4th Avenue - 4 months ago 7
PHP Question

Unable to access value from PHP Object

I was trying a shipment API. The API returns object. But when I try to access a certain value using a simple

foreach
loop, it does not work as intended. I tried different methods but everything gives me a blank page.

Following is the response received from the API.

stdClass Object
(
[ConsignmentTrackEvents_Details_NewResult] => stdClass Object
(
[ConsignmentTrack] => Array
(
[0] => stdClass Object
(
[ERROR] =>
[DOCKNO] => 888888
[TRANSIT_LOCATION] => Location, Location
[ACTIVITY] => Out For Delivery
[EVENTDATE] => 22 Jul 2016
[EVENTTIME] => 21:05:48
[NEXT_LOCATION] => Coimbatore
[TRACKING_CODE] => O
)

[1] => stdClass Object
(
[ERROR] =>
[DOCKNO] => 888888
[TRANSIT_LOCATION] => Location, Location
[ACTIVITY] => Picked up and Booking processed
[EVENTDATE] => 06 Jun 2016
[EVENTTIME] => 16:40:39
[NEXT_LOCATION] =>
[TRACKING_CODE] => B
)

)

)

)


Then I used the following loop to access the values.

foreach($result['ConsignmentTrackEvents_Details_NewResult'] ['ConsignmentTrack'] as $res){

echo $res['DOCKNO'];

}


Am I doing anything wrong here?

Answer

Array and Object are different things, you access array entry with $array['key'] and object property with $object->key

foreach($result->ConsignmentTrackEvents_Details_NewResult->ConsignmentTrack as $res){
    echo $res->DOCKNO;
}