6

我是在 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编程,所以我希望能不吝赐教。谢谢!

4

3 回答 3

3

使用对象和数组的一个开始是将对象用于somethings,将数组用于somethings的列表(0,1, many, lot) 。过于简单化了,但它让事情开始了。当对象可以回答有关自己的问题时(这列火车是否停在 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'));

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


    类站{

            公共函数 goToDestination($destination) {
                $aReturn = 数组();
                foreach ($this->ITEMS as $oScheduledDeparture) {
                    if ($oScheduledDeparture->goesToStation($destination)) {
                        $aReturn[] = $oScheduledDeparture;
                    }
                }
                返回 $aReturn;
            }

            公共函数 getConnections($destination, $connection_time) {
                $aReturn = 数组();
                foreach ($this->ITEMS as $oScheduledDeparture) {
                    if ($oScheduledDeparture->goesToStation($destination)) {
                        $aReturn[] = 数组(
                            'SCHED_DEP_DATE' => $oScheduledDeparture->SCHED_DEP_DATE,
                            'DESTINATION' => $oScheduledDeparture->DESTINATION,
                            'CONNECTION' => $oScheduledDeparture->getConnection($destination, $connection_time),
                        );
                    }
                }
                返回 $aReturn;
            }

        }

        功能生成站(){

            $aStation = 数组(
                STATION_2CHAR => 'ST',
                STATIONNAME => '峰会',
            );

            $oStation = 新站();
            foreach ($aItem as $key=>$value) {
                $oStation->$key = $value;
            }

            $oStation->项目 = 数组(
                generate_scheduled_departure_0(),
                generate_scheduled_departure_1(),
            );
            返回$oStation;
        }

        类预定出发{

            公共函数 getScheduledDepartureTime() {
                返回 $this->SCHED_DEP_DATE;
            }

            公共函数 goToStation($destination) {
                if ($this->DESTINATION == $destination) {
                    返回真;
                }

                // 检查停止
                foreach ($this->STOPS as $STOP) {
                    if ($STOP->NAME == $destination) {
                        返回真;
                    }
                }
                返回假;
            }

            公共函数 getConnection($destination, $connection_time) {
                $connect_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $connection_time);
                $xfer_depart_raw = DateTime::createFromFormat("H:i:sm/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);

                        如果($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");
                            返回数组 ($xfer,$final);
                        }
                    }
                 }
                 // 没有可用的连接
                 返回假;
            }
        }

        功能 generate_scheduled_departure_0() {
            $aItem = 数组(
                'ITEM_INDEX' => '0',
                'SCHED_DEP_DATE' => '07:55:00 08/02/2013',
                '目的地' => '多佛',
                '轨道' => '1',
                'LINE' => '机电',
                'TRAIN_ID' => '6607',
                '状态' => '全部登机',
                'SEC_LATE' => '322',
                'BACKCOLOR' => '绿色',
                '前色' => '白色',
                'SHADOWCOLOR' => '黑色',
                'GPSLATITUDE' => '',
                'GPS经度' => '',
                'GPSTIME' => '8/2/2013 7:59:37 AM',
                'TRAIN_LINE' => '莫里斯和埃塞克斯线',
                'STATION_POSITION' => '1',
                'LINEABBRVIATION' => 'M&E',
                'INLINEMSG' => '',
            );

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

            $oScheduleDeparture->STOPS = generate_scheduled_departure_0_stops();
            返回$oScheduleDeparture;
        }

        功能 generate_scheduled_departure_0_stops() {

            $aStops = 数组();

            //
            $aStop = 数组(
                'NAME' => '查塔姆',
                '时间' => '8/2/2013 8:05:31 AM',
            );
            $aStops[] = (对象)$aStop;

            $aStop = 数组(
                'NAME' => '麦迪逊',
                '时间' => '8/2/2013 8:08:43 AM',
            );
            $aStops[] = (对象)$aStop;

            $aStop = 数组(
                'NAME' => '修道院站',
                '时间' => '8/2/2013 8:12:56 AM',
            );
            $aStops[] = (对象)$aStop;

            返回$aStops;
        }

        // 项目 1
        函数 generate_scheduled_departure_1() {
            $aItem = 数组(
                'ITEM_INDEX' => '1',
                'SCHED_DEP_DATE' => '08:07:00 08/02/2013',
                '目的地' => '霍博肯',
                '轨道' => '2',
                'LINE' => '机电',
                'TRAIN_ID' => '414',
                '状态' => '在 8 分钟内',
                'SEC_LATE' => '81',
                'BACKCOLOR' => '浅绿色',
                '前色' => '黑色',
                'SHADOWCOLOR' => '浅绿色',
                'GPSLATITUDE' => '40.6951',
                'GPS经度' => '-74.4034',
                'GPSTIME' => '8/2/2013 7:59:59 AM',
                'TRAIN_LINE' => '格莱斯顿分公司',
                'STATION_POSITION' => '1',
                'LINEABBRVIATION' => 'M&E',
                'INLINEMSG' => '',
            );

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

            $oScheduleDeparture->STOPS = generate_schedule_departure_1_stops();
            返回$oScheduleDeparture;
        }

        功能 generate_scheduled_departure_1_stops() {

            $aStops = 数组();

            $aStop = 数组(
                'NAME' => '枫木',
                '时间' => '8/2/2013 8:14:53 AM',
            );
            $aStops[] = (对象)$aStop;

            $aStop = 数组(
                'NAME' => '南橙',
                '时间' => '8/2/2013 8:08:43 AM',
            );
            $aStops[] = (对象)$aStop;

            $aStop = 数组(
                'NAME' => '修道院站',
                '时间' => '8/2/2013 8:14:25 AM',
            );
            $aStops[] = (对象)$aStop;

            返回$aStops;
        }
于 2013-08-16T20:00:21.540 回答
0

同时使用两种数据类型是地狱,你很难过你有 json 数据。所以当你解码json时传递true。这样每件事都将转换为数组。

当您传递 TRUE 时,返回的对象将被转换为关联数组。

print_r(json_decode($json_data, true));

如果您没有 json 数据,则只需先编码为 json,然后对其进行解码。因为没有其他方法可以将所有 Std 类转换为数组(或 stdClass)中的数组。

print_r(json_decode(json_encode($data), true));

使用一种数据类型比使用两种更容易。希望这会有所帮助。

于 2013-08-16T15:55:50.410 回答
0

我认为它看起来不错,除了您不需要更新$connect_raw$xfer_depart_raw每次内部迭代,因为源值不会改变。此外,您可以$xfer_depart_raw > $connect_raw更早地做出决定,因为两个值在内循环中都不会改变:

// $trip is the Object from the above data sample.
function get_connection($trip,$final_desired_dest,$connection_time) {
    $connect_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $connection_time);
    foreach ($trip as $st_key=>$st_ny_trip) {
        $xfer_depart_time = $st_ny_trip->SCHED_DEP_DATE;
        $xfer_depart_raw = DateTime::createFromFormat("H:i:s m/d/Y", $xfer_depart_time);

        if ($xfer_depart_raw <= $connect_raw)
            continue;

        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) {
                $final_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $value->TIME);
                $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);
            }
        }
    } // foreach (first)
    return array ("","");
} // function end

另一种方法是使用array_walk闭包:

// $trip is the Object from the above data sample.
function get_connection($trip,$final_desired_dest, $connection_time) {
    $result = array("", "");
    try {
        array_walk($trip, function(&$st_ny_trip, $st_key) use (&$result) {
            $xfer_depart_time = $st_ny_trip->SCHED_DEP_DATE;
            $xfer_depart_raw = DateTime::createFromFormat("H:i:s m/d/Y", $xfer_depart_time);
            if ($xfer_depart_raw > $connect_raw) {
                array_walk(array($st_ny_trip->STOPS->STOP), function(&$value, $key) use (&$result) {
                    if ($value->NAME == $final_desired_dest) {
                        $final_raw = DateTime::createFromFormat("m/d/Y g:i:s a", $value->TIME);
                        $xfer = $xfer_depart_raw->format("m/d/Y g:i:s a");
                        $final = $final_raw->format("m/d/Y g:i:s a");
                        $result = array($xfer, $final);
                        throw new Exception(); // get out
                    }
                });
            }
        });
    } catch (Exception $e) {
    }
    return $result;
} // function end
于 2013-08-10T09:20:48.543 回答