我正在尝试装运API。 API返回对象。但是当我尝试使用简单的foreach
循环访问某个值时,它无法正常工作。我尝试了不同的方法,但一切都给了我一个空白页面。
以下是从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
)
)
)
)
然后我使用以下循环来访问值。
foreach($result['ConsignmentTrackEvents_Details_NewResult'] ['ConsignmentTrack'] as $res){
echo $res['DOCKNO'];
}
我在这里做错了吗?
答案 0 :(得分:2)
数组和对象是不同的东西,您使用$array['key']
访问数组条目,使用$object->key
访问对象属性
foreach($result->ConsignmentTrackEvents_Details_NewResult->ConsignmentTrack as $res){
echo $res->DOCKNO;
}
答案 1 :(得分:0)
您可以使用foreach
循环遍历主集合,然后向下钻取到其中包含的对象,该对象(反过来)包含您要查找的数据。
<?php
// $result HERE IS THE MAIN DATA...
foreach($result as $key=>$data){
$trackResult = $result['ConsignmentTrackEvents_Details_NewResult'];
foreach($trackResult as $intKey=>$objData){
$dockNo = $objData->DOCKNO;
$transit = $objData->TRANSIT_LOCATION;
$activity = $objData->ACTIVITY;
$eventDate = $objData->EVENTDATE;
$eventTime = $objData->EVENTTIME;
$nextLocation = $objData->NEXT_LOCATION;
$trackingCode = $objData->TRACKING_CODE;
echo $dockNo;
}
}