如何使用数组处理对象以访问特定数据?

Edw*_*ard 6 php arrays oop foreach object

我刚开始使用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
Run Code Online (Sandbox Code Playgroud)

这是我用来访问这些数据的PHP编码方法.我想知道是否有更好的方法,因为它变得有点复杂,不得不"循环"循环通过它来获得我需要的东西.我对PHP中的Objects有了印象,我可以更直接地访问数据.

这是我写的一些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
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更好的方法来改进这一点.我可能会非常忽略如何在这里充分利用Objects和OO编程,所以我期待着能够启发.谢谢!

Ste*_*ynn 3

使用对象和数组的开始是使用对象表示某些东西,使用数组表示某些东西的列表(0,1,很多,很多)。过于简单化,但它让事情开始了。当对象可以回答有关自身的问题(这列火车停在 X 吗?)时,对象特别有用,因为您只需编写一次代码即可经常使用它。

由于您拥有 JSON 格式的对象并显示了print_r,我假设您能够将原始数据转换为您想要的任何格式。您显示的格式有一些数据交换所需的额外字段,但在编程中使用它时可能是多余的。我建议删除无用的字段/级别(例如STOPS中的STOP)并将列表转换为数组,将其他项目转换为对象。

我将数据强行转换为我在下面使用的结构。它允许这样的代码:

    $oScheduleDeparture = generate_scheduled_departure_1();
    $oStation = generate_station();

    print_r($oScheduleDeparture->getConnection('Madison', '3/4/2013 3:14:00 AM'));
    print_r($oStation->goesToDestination('Hoboken'));
    print_r($oStation->getConnections('Madison', '3/4/2013 3:14:00 AM'));
Run Code Online (Sandbox Code Playgroud)

您应该能够编写一个解析器将原始数据转换为类似的数据。希望能帮助到你!


    class Station {

            public function goesToDestination($destination) {
                $aReturn = array();
                foreach ($this->ITEMS as $oScheduledDeparture) {
                    if ($oScheduledDeparture->goesToStation($destination)) {
                        $aReturn[] = $oScheduledDeparture;
                    }
                }
                return $aReturn;
            }

            public function getConnections($destination, $connection_time) {
                $aReturn = array();
                foreach ($this->ITEMS as $oScheduledDeparture) {
                    if ($oScheduledDeparture->goesToStation($destination)) {
                        $aReturn[] = array(
                            'SCHED_DEP_DATE'    => $oScheduledDeparture->SCHED_DEP_DATE,
                            'DESTINATION'       => $oScheduledDeparture->DESTINATION,
                            'CONNECTION'        => $oScheduledDeparture->getConnection($destination, $connection_time),
                        );
                    }
                }
                return $aReturn;
            }

        }

        function generate_station() {

            $aStation = array(
                STATION_2CHAR   => 'ST',
                STATIONNAME     => 'Summit',
            );

            $oStation = new Station();
            foreach ($aItem as $key=>$value) {
                $oStation->$key = $value;
            }

            $oStation->ITEMS = array(
                generate_scheduled_departure_0(),
                generate_scheduled_departure_1(),
            );
            return $oStation;
        }

        class ScheduledDeparture {

            public function getScheduledDepartureTime() {
                return $this->SCHED_DEP_DATE;
            }

            public function goesToStation($destination) {
                if ($this->DESTINATION == $destination) {
                    return true;
                }

                // check stops
                foreach ($this->STOPS as $STOP) {
                    if ($STOP->NAME == $destination) {
                        return true;
                    }
                }
                return false;
            }

            public function getConnection($destination, $connection_time) {
                $connect_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $connection_time);
                $xfer_depart_raw = DateTime::createFromFormat("H:i:s m/d/Y", $this->getScheduledDepartureTime());

                foreach ($this->STOPS as $STOP) {
                    if ($STOP->NAME == $destination) {
                        $final_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $STOP->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);
                        } 
                    }
                 }
                 // no connection available
                 return false;
            }
        }

        function generate_scheduled_departure_0() {
            $aItem = array(
                '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'         => '',
            );

            $oScheduleDeparture = new ScheduledDeparture();
            foreach ($aItem as $key=>$value) {
                $oScheduleDeparture->$key = $value;
            }

            $oScheduleDeparture->STOPS = generate_scheduled_departure_0_stops();
            return $oScheduleDeparture;
        }

        function generate_scheduled_departure_0_stops() {

            $aStops = array();

            // 
            $aStop = array(
                'NAME' => 'Chatham',
                'TIME' => '8/2/2013 8:05:31 AM',
            );
            $aStops[] = (object)$aStop;

            $aStop = array(
                'NAME' => 'Madison',
                'TIME' => '8/2/2013 8:08:43 AM',
            );
            $aStops[] = (object)$aStop;

            $aStop = array(
                'NAME' => 'Convent Station',
                'TIME' => '8/2/2013 8:12:56 AM',
            );
            $aStops[] = (object)$aStop;

            return $aStops;
        }

        // item 1
        function generate_scheduled_departure_1() {
            $aItem = array(
                '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'         => '',
            );

            $oScheduleDeparture = new ScheduledDeparture();
            foreach ($aItem as $key=>$value) {
                $oScheduleDeparture->$key = $value;
            }

            $oScheduleDeparture->STOPS = generate_scheduled_departure_1_stops();
            return $oScheduleDeparture;
        }

        function generate_scheduled_departure_1_stops() {

            $aStops = array();

            $aStop = array(
                'NAME' => 'Maplewood',
                'TIME' => '8/2/2013 8:14:53 AM',
            );
            $aStops[] = (object)$aStop;

            $aStop = array(
                'NAME' => 'South Orange',
                'TIME' => '8/2/2013 8:08:43 AM',
            );
            $aStops[] = (object)$aStop;

            $aStop = array(
                'NAME' => 'Convent Station',
                'TIME' => '8/2/2013 8:14:25 AM',
            );
            $aStops[] = (object)$aStop;

            return $aStops;
        }