PHP将对象转换为数组并访问数组部分

时间:2018-01-22 16:04:29

标签: php

我正在开展一个小项目,要求英国国家铁路公司提供数据。我有这个部分工作,返回的数据是一个对象。如何将数据对象转换为数组,并能够访问该数组的选定部分。

我的数据对象如下:

stdClass Object
(
[GetStationBoardResult] => stdClass Object
    (
        [generatedAt] => 2018-01-22T16:08:03.2671614+00:00
        [locationName] => London Paddington
        [crs] => PAD
        [nrccMessages] => stdClass Object
            (
                [message] => stdClass Object
                    (
                        [_] => <P>Trains at Oxford may be cancelled, delayed or revised. More information can be found in <A href="http://nationalrail.co.uk/service_disruptions/182185.aspx">Latest Travel News</A></P>
                    )

            )

        [platformAvailable] => 1
        [trainServices] => stdClass Object
            (
                [service] => stdClass Object
                    (
                        [std] => 15:45
                        [etd] => Delayed
                        [operator] => Great Western Railway
                        [operatorCode] => GW
                        [serviceType] => train
                        [delayReason] => This train has been delayed by a shortage of train drivers
                        [serviceID] => U1uclHPAaZ+YyHhPMfca1A==
                        [rsid] => GW611100
                        [origin] => stdClass Object
                            (
                                [location] => stdClass Object
                                    (
                                        [locationName] => London Paddington
                                        [crs] => PAD
                                    )

                            )

                        [destination] => stdClass Object
                            (
                                [location] => stdClass Object
                                    (
                                        [locationName] => Swansea
                                        [crs] => SWA
                                    )

                            )

                    )

            )

    )

)

Var Dump。

array(1) {
    ["GetStationBoardResult"]=>
    object(stdClass)#6 (6) {
    ["generatedAt"]=>
    string(33) "2018-01-22T15:56:58.6642415+00:00"
    ["locationName"]=>
    string(17) "London Paddington"
    ["crs"]=>
    string(3) "PAD"
    ["nrccMessages"]=>
    object(stdClass)#7 (1) {
    ["message"]=>
    object(stdClass)#8 (1) {
    ["_"]=>
    string(185) "<P>Trains at Oxford may be cancelled, delayed or revised. More information can be found in <A href="http://nationalrail.co.uk/service_disruptions/182185.aspx">Latest Travel News</A></P>"
    }
    }
    ["platformAvailable"]=>
    bool(true)
    ["trainServices"]=>
    object(stdClass)#9 (1) {
    ["service"]=>
    object(stdClass)#10 (10) {
    ["std"]=>
    string(5) "15:45"
    ["etd"]=>
    string(7) "Delayed"
    ["operator"]=>
    string(21) "Great Western Railway"
    ["operatorCode"]=>
    string(2) "GW"
    ["serviceType"]=>
    string(5) "train"
    ["delayReason"]=>
    string(58) "This train has been delayed by a shortage of train drivers"
    ["serviceID"]=>
    string(24) "U1uclHPAaZ+YyHhPMfca1A=="
    ["rsid"]=>
    string(8) "GW611100"
    ["origin"]=>
    object(stdClass)#11 (1) {
    ["location"]=>
    object(stdClass)#12 (2) {
    ["locationName"]=>
    string(17) "London Paddington"
    ["crs"]=>
    string(3) "PAD"
    }
    }
    ["destination"]=>
    object(stdClass)#13 (1) {
    ["location"]=>
    object(stdClass)#14 (2) {
    ["locationName"]=>
    string(7) "Swansea"
    ["crs"]=>
    string(3) "SWA"
    }
    }
    }
    }
    }
}

任何人都可以告诉我如何做到这一点。 非常感谢你的时间。

RAW DATA有3条记录

object(stdClass)#5 (1) {
["GetStationBoardResult"]=>
object(stdClass)#6 (5) {
["generatedAt"]=>
string(33) "2018-01-23T12:35:38.6358435+00:00"
["locationName"]=>
string(17) "London Paddington"
["crs"]=>
string(3) "PAD"
["platformAvailable"]=>
bool(true)
["trainServices"]=>
object(stdClass)#7 (1) {
  ["service"]=>
  array(3) {
    [0]=>
    object(stdClass)#8 (9) {
      ["std"]=>
      string(5) "12:33"
      ["etd"]=>
      string(5) "12:35"
      ["operator"]=>
      string(16) "Heathrow Connect"
      ["operatorCode"]=>
      string(2) "HC"
      ["serviceType"]=>
      string(5) "train"
      ["serviceID"]=>
      string(24) "rnsoBNmZejPq0MYoqh4RrA=="
      ["rsid"]=>
      string(8) "HC010500"
      ["origin"]=>
      object(stdClass)#9 (1) {
        ["location"]=>
        object(stdClass)#10 (2) {
          ["locationName"]=>
          string(17) "London Paddington"
          ["crs"]=>
          string(3) "PAD"
        }
      }
      ["destination"]=>
      object(stdClass)#11 (1) {
        ["location"]=>
        object(stdClass)#12 (2) {
          ["locationName"]=>
          string(21) "Heathrow Airport T123"
          ["crs"]=>
          string(3) "HXX"
        }
      }
    }
    [1]=>
    object(stdClass)#13 (10) {
      ["std"]=>
      string(5) "12:40"
      ["etd"]=>
      string(7) "On time"
      ["platform"]=>
      string(2) "12"
      ["operator"]=>
      string(16) "Heathrow Express"
      ["operatorCode"]=>
      string(2) "HX"
      ["serviceType"]=>
      string(5) "train"
      ["serviceID"]=>
      string(24) "Ti/5lChQ5BZgVT/8gmULBA=="
      ["rsid"]=>
      string(8) "HX010000"
      ["origin"]=>
      object(stdClass)#14 (1) {
        ["location"]=>
        object(stdClass)#15 (2) {
          ["locationName"]=>
          string(17) "London Paddington"
          ["crs"]=>
          string(3) "PAD"
        }
      }
      ["destination"]=>
      object(stdClass)#16 (1) {
        ["location"]=>
        object(stdClass)#17 (2) {
          ["locationName"]=>
          string(19) "Heathrow Airport T5"
          ["crs"]=>
          string(3) "HWV"
        }
      }
    }
    [2]=>
    object(stdClass)#18 (10) {
      ["std"]=>
      string(5) "12:42"
      ["etd"]=>
      string(7) "On time"
      ["platform"]=>
      string(2) "14"
      ["operator"]=>
      string(21) "Great Western Railway"
      ["operatorCode"]=>
      string(2) "GW"
      ["serviceType"]=>
      string(5) "train"
      ["serviceID"]=>
      string(24) "H+VXbe2oimkbSMAGgS4vBQ=="
      ["rsid"]=>
      string(8) "GW756600"
      ["origin"]=>
      object(stdClass)#19 (1) {
        ["location"]=>
        object(stdClass)#20 (2) {
          ["locationName"]=>
          string(17) "London Paddington"
          ["crs"]=>
          string(3) "PAD"
        }
      }
      ["destination"]=>
      object(stdClass)#21 (1) {
        ["location"]=>
        object(stdClass)#22 (2) {
          ["locationName"]=>
          string(7) "Twyford"
          ["crs"]=>
          string(3) "TWY"
        }
      }
    }
  }
}
}
}

嗨RamRaider,我有一个最后的问题。 当&#34;服务&#34; array包含沿着路径的站点呼叫点的数据如何读取每个位置的变量。

我尝试根据您的示例使用以下代码,但无论出于何种原因我都无法访问变量。

if( is_array( $callingAt ) ){
  /* Multiple records */

  /* an array of objects */
  foreach( $callingAt as $index => $obj ){
    $keys=array_keys( get_object_vars( $obj ) );
    //print_r ($keys);

    foreach( $keys as $key ){
      ${$key}=$obj->$key;

      //print_r (${$key});

      printf("<pre>\nStation: %s\n</pre>\n", $locationName->subsequentCallingPoints->callingPointList->callingPoint );
    }
  }
}

Code with the calling points

    stdClass Object  (
   [GetStationBoardResult] => stdClass Object (
      [generatedAt] => 2018-01-26T10:34:47.9177301+00:00
      [locationName] => London Euston
      [crs] => EUS
      [platformAvailable] => 1
      [trainServices] => stdClass Object (
         [service] => Array (
           [0] => stdClass Object (
             [std] => 10:34
             [etd] => On time
             [platform] => 11
             [operator] => West Midlands Trains
             [operatorCode] => LM
             [serviceType] => train
             [serviceID] => JsXOPFy5xbo8LmsvGLTj8Q==
             [rsid] => LM318200
             [origin] => stdClass Object  (
               [location] => stdClass Object (
                 [locationName] => London Euston
                 [crs] => EUS
               )
                 )

         [destination] => stdClass Object (
           [location] => stdClass Object (
             [locationName] => Tring
             [crs] => TRI
            )
             )

    [subsequentCallingPoints] => stdClass Object (
     [callingPointList] => stdClass Object (
       [callingPoint] => Array (
        [0] => stdClass Object (
         [locationName] => Harrow & Wealdstone
         [crs] => HRW
         [st] => 10:46
         [et] => On time
        )

      [1] => stdClass Object (
           [locationName] => Bushey
           [crs] => BSH
           [st] => 10:51
           [et] => On time
         )
  )

  [serviceType] => train
  [serviceChangeRequired] =>
  [assocIsCancelled] =>
)
)
)

1 个答案:

答案 0 :(得分:1)

为了演示如何访问数据的组成部分,我重新创建了这样的对象数据。据推测,这是来自铁路API的json字符串,您已将其解码为对象。

$data=(object)array(
    'GetStationBoardResult'=>(object)array(
        'generatedAt'   =>  '2018-01-22T16:08:03.2671614+00:00',
        'locationName'  =>  'London Paddington',
        'crs'           =>  'PAD',
        'nrccMessages'  =>  (object)array(
            'message'   =>  (object)array(
                '_' =>  '<P>Trains at Oxford may be cancelled, delayed or revised. More information can be found in <A href="http://nationalrail.co.uk/service_disruptions/182185.aspx">Latest Travel News</A></P>'
            )
        ),
        'platformAvailable' =>  1,
        'trainServices'     =>  (object)array(
            'service'   =>  array(
                (object)array(
                    'std'           =>  '15:45',
                    'etd'           =>  'Delayed',
                    'operator'      =>  'Great Western Railway',
                    'operatorCode'  =>  'GW',
                    'serviceType'   =>  'train',
                    'delayReason'   =>  'This train has been delayed by a shortage of train drivers',
                    'serviceID'     =>  'U1uclHPAaZ+YyHhPMfca1A==',
                    'rsid'          =>  'GW611100',
                    'origin'        =>  (object)array(
                        'location'  =>  (object)array(
                            'locationName'  =>  'London Paddington',
                            'crs'           =>  'PAD'
                        )
                    ),
                    'destination'   =>  (object)array(
                        'location'  =>  (object)array(
                            'locationName'  =>  'Swansea',
                            'crs'           =>  'SWA'
                        )
                    )
                ),
                (object)array(
                    'std'           =>  '12:25',
                    'etd'           =>  'On time',
                    'operator'      =>  'Heathrow Express',
                    'operatorCode'  =>  'HX',
                    'serviceType'   =>  'train',
                    'delayReason'   =>  'This train is unusual - it is not late',
                    'serviceID'     =>  'voGWZn1GnW5o3TnqXptUXg',
                    'rsid'          =>  'HX010000',
                    'origin'        =>  (object)array(
                        'location'  =>  (object)array(
                            'locationName'  =>  'London Paddington',
                            'crs'           =>  'PAD'
                        )
                    ),
                    'destination'   =>  (object)array(
                        'location'  =>  (object)array(
                            'locationName'  =>  'Heathrow Airport T5',
                            'crs'           =>  'HWV'
                        )
                    )
                )
            )
        )
    )
);










/* Get reference to the parent node in data structure */
$results=$data->GetStationBoardResult;
/* 
    The direct child elements of the parent 
    are  easily accessible using object notation 
*/
$generatedAt=$results->generatedAt;
$locationName=$results->locationName;
$crs=$results->crs;
$message=$results->nrccMessages->message->{'_'}; /* looks like a smiley face ~ not sure that's possible on British trains! */
$platform=$results->platformAvailable;

/* The services... */
$service=$results->trainServices->service;
if( is_array( $service ) ){
    /* Multiple records */

    /* an array of objects */
    foreach( $service as $index => $obj ){
        $keys=array_keys( get_object_vars( $obj ) );

        foreach( $keys as $key ){
            ${$key}=$obj->$key;
        }

        printf("<pre>Time: %s\nOperator: %s\nServiceID: %s</pre>", $std, $operator, $serviceID );
    }


} else {
    /* Single record */

    /* if we get the keys we can loop through them */
    $keys=array_keys( get_object_vars( $service ) );

    foreach( $keys as $key ){
        /* 
            You could generate variable variables from the data at this point
            which would allow you to access them as variables such as 

            $delayReason or $std etc ( vars named the same as the keys )
        */ 
        ${$key}=$service->$key;

        /*
            or
            printf('<p>%s: %s</p>', $key, $service->$key ); etc
        */
    }
    /*
        The services have `origin` and `destination`
        so you can access these like this 
        ( assuming variable variables as above )
    */
    $origin_location=$origin->location->locationName;
    $origin_crs=$origin->location->crs;

    /* and */

    $dest_location=$destination->location->locationName;
    $dest_crs=$destination->location->crs;


    /* Or, without variable variables... */
    $dest_location=$service->destination->location->locationName;

}

对于调用点,如果我正确地重新构建了结构,那么就像这样:

$subsequentCallingPoints=$results->subsequentCallingPoints;
$callingPointList=$subsequentCallingPoints->callingPointList;
$callingPoint=$callingPointList->callingPoint;

/* or */
$callingPoint=$results->subsequentCallingPoints->callingPointList->callingPoint;

foreach( $callingPoint as $obj ){
    $locationName=$obj->locationName;
    $crs=$obj->crs;

    printf('callingPoint -> $locationName=%s, $crs=%s<br />', $locationName, $crs );
}