php cURL 未定义索引

php cURL undefined index

我正在从检索到的 json 数组中返回值。我可以解析一些数据但不能解析其他数据,下面是我试图提取的数据的视图:

代码:

<?php
  $headers = array( //Set headers data
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("Username removed:Password removed") //Set basic authentication
);
  $today = date('Y/m/d');
  $serviceUid='W96397';
  $ch = curl_init('https://api.rtt.io/api/v1/json/service/'.$serviceUid.'/'.$today);//serviceUid is set here
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch,CURLOPT_ENCODING, "");            //Set gzip decoding
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);      //not sure
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);   //Set headers in curl options, set previously
  $result=curl_exec($ch);                           //Execute and retrive data
  curl_close($ch);
  $result_arr = json_decode($result, true);

        $serviceUid= $result_arr['serviceUid']; //works fine
        $runningIdentity = $result_arr['runningIdentity']; //works fine

        //All commented out bellow do not return any data*********

        foreach($result_arr['locations'] as $locations){
             $crs = $locations['crs'];
        //   $gbttBookedDeparture = $locations['gettBookedDeparture'];
             $isCall = $locations['isCall'];
             $isPublicCall = $locations['isPublicCall'];
        //   $realtimeDeparture = $locations['realtimeDeparture'];
        //   $realtimeDepartureActual = $locations['realtimeDepartureActual'];
        //   $platform = $locations['platform'];
        //   $platformConfirmed = $locations['platformConfirmed'];
        //   $platformChanged = $locations['platformChanged'];
             $displayAs = $locations['displayAs'];
         }
  ?>                

错误是:PHP注意:/var/www/html/serviceDetails.php 行 php 中的未定义索引:平台[行号]

编辑:JSON 数据:pastebin.com/raw.php?i=P5A7s1Ur

根据您提供的数据文件,某些元素不包括 'platform' 属性(请参阅此处的示例)。

所以使用我之前建议的技巧:

$platform = (isset($locations['platform']))?$locations['platform']:'';

您应该在使用前验证 属性 是否存在。

代码:

foreach($result_arr['locations'] as $locations){

   $platform = (isset($locations['platform']))?$locations['platform']:'';
   echo '== PLATFORM : '.$platform.' <br />';
}

输出: == PLATFORM : 7 == PLATFORM : 9 == PLATFORM : 4 == PLATFORM : 2 == PLATFORM : 2 == PLATFORM : 3 == PLATFORM : == PLATFORM : 1 == PLATFORM : == PLATFORM : 2 == PLATFORM : 2 == PLATFORM : == PLATFORM : 1 == PLATFORM : 1 == PLATFORM : == PLATFORM : == PLATFORM : == PLATFORM : 2 == PLATFORM : 3