我是在 PHP 中处理对象的新手。我有一个带有 print_r 输出的 JSON 对象,看起来像这样(请参见下文)。我已经对其进行了编辑以缩短它,但这是它的结构:
stdClass Object
(
[STATION_2CHAR] => ST
[STATIONNAME] => Summit
[ITEMS] => stdClass Object
(
[ITEM] => Array
(
[0] => stdClass Object
(
[ITEM_INDEX] => 0
[SCHED_DEP_DATE] => 07:55:00 08/02/2013
[DESTINATION] => Dover
[TRACK] => 1
[LINE] => M&E
[TRAIN_ID] => 6607
[STATUS] => All Aboard
[SEC_LATE] => 322
[BACKCOLOR] => green
[FORECOLOR] => white
[SHADOWCOLOR] => black
[GPSLATITUDE] =>
[GPSLONGITUDE] =>
[GPSTIME] => 8/2/2013 7:59:37 AM
[TRAIN_LINE] => Morris & Essex Line
[STATION_POSITION] => 1
[LINEABBREVIATION] => M&E
[INLINEMSG] =>
[STOPS] => stdClass Object
(
[STOP] => Array
(
[0] => stdClass Object
(
[NAME] => Chatham
[TIME] => 8/2/2013 8:05:31 AM
)
[1] => stdClass Object
(
[NAME] => Madison
[TIME] => 8/2/2013 8:08:43 AM
)
[2] => stdClass Object
(
[NAME] => Convent Station
[TIME] => 8/2/2013 8:12:56 AM
)
... etc
)
)
)
[1] => stdClass Object
(
[ITEM_INDEX] => 1
[SCHED_DEP_DATE] => 08:07:00 08/02/2013
[DESTINATION] => Hoboken
[TRACK] => 2
[LINE] => M&E
[TRAIN_ID] => 414
[STATUS] => in 8 Min
[SEC_LATE] => 81
[BACKCOLOR] => lightgreen
[FORECOLOR] => black
[SHADOWCOLOR] => lightgreen
[GPSLATITUDE] => 40.6951
[GPSLONGITUDE] => -74.4034
[GPSTIME] => 8/2/2013 7:59:59 AM
[TRAIN_LINE] => Gladstone Branch
[STATION_POSITION] => 1
[LINEABBREVIATION] => M&E
[INLINEMSG] =>
[STOPS] => stdClass Object
(
[STOP] => Array
(
[0] => stdClass Object
(
[NAME] => Maplewood
[TIME] => 8/2/2013 8:14:53 AM
)
[1] => stdClass Object
(
[NAME] => South Orange
... etc
这是我用来访问这些数据的 PHP 编码方法类型。我想知道是否有更好的方法,因为它变得有点复杂,必须通过它“foreach”循环才能得到我需要的东西。我对 PHP 中的对象有印象,我可以更直接地访问数据。
这是我写的一些 PHP 代码。这是一个函数,虽然到目前为止我对它进行了单元测试,但我觉得有更好的方法来做到这一点,以便在编程中更加优雅。该函数有两个嵌套的 foreach 循环和三个“if”语句。对我来说,找到旅行的连接时间似乎很重要。
// $trip is the Object from the above data sample.
function get_connection($trip,$final_desired_dest,$connection_time) {
foreach ($trip as $st_key=>$st_ny_trip) {
$xfer_depart_time = $st_ny_trip->SCHED_DEP_DATE;
if ($st_ny_trip->STOPS->STOP instanceof stdClass)
{
$st_ny_trip->STOPS->STOP = array($st_ny_trip->STOPS->STOP);
}
foreach ($st_ny_trip->STOPS->STOP as $key=>$value) {
if ($value->NAME == $final_desired_dest ) {
$connect_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $connection_time);
$xfer_depart_raw = DateTime::createFromFormat("H:i:s m/d/Y", $xfer_depart_time);
$final_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $value->TIME);
if ($xfer_depart_raw > $connect_raw) {
$xfer = $xfer_depart_raw->format("m/d/Y g:i:s a");
$final = $final_raw->format("m/d/Y g:i:s a");
return array ($xfer,$final);
} // if (second)
} // if (first)
}
} // foreach (first)
return array ("","");
} // function end
我正在寻找一种更好的方法来改进这一点。我可能会大大忽略如何充分利用这里的Objects和OO编程,所以我希望能不吝赐教。谢谢!