2015-07-03 55 views
1

我想爲我的項目使用這個鐵路API。如果我輸入一個正確的數字,那麼它可以很好地工作,但如果我輸入一個隨機的10位數字,那麼我會收到第20行和第21行中未定義的偏移量:0錯誤。我對此很陌生,而且我已經搜索了很多解決方案,找不到任何東西。未定義的偏移量0在PHP中的json值

<?php 
$json = ''; 
if(isset($_POST['pnrQ'])){ 
    $searchParam = $_POST['pnrQ']; 
$replacedStr = str_replace(" ","",$searchParam); 
$url = 'http://api.railwayapi.com/pnr_status/pnr/'.$replacedStr.'/apikey//'; 
$content = file_get_contents($url); 
$json = json_decode($content, true); 
}else{ 
    echo "something went wrong, please notify to admin [[email protected]]"; 
} 
$dateOfJourney = $json['doj']; 
$pnr = $json['pnr']; 
$fromStation = $json['from_station']['name']; 
$fromStationCd = $json['from_station']['code']; 
$toStation = $json['to_station']['name']; 
$toStationCd = $json['to_station']['code']; 
$trainNum = $json['train_num']; 
$trainName = $json['train_name']; 
$currStatus = $json['passengers'][0]['current_status']; //line 20 
$bookingStatus = $json['passengers'][0]['booking_status']; //line 21 
$isChartPrep = $json['chart_prepared']; 
$isChartPrepd = ($isChartPrep=='N') ? 'NO' : 'YES'; 
$cls = $json['class']; 
$totPass = $json['total_passengers']; 
?> 
+0

其中沒有。你插入和談論? – Vinay

+0

打印json變量並檢查值 –

+0

發佈您的$ json數據 – rocky

回答

0

使用var_exportprint_r功能檢查究竟在$ JSON [「乘客」]

可能是JSON值具有不同的結構。

編輯:

可能是由於輸入錯誤,你得到了JSON的答覆具有不同的結構。所以你可以先檢查出來,然後使用if條件來查看特定的數組元素是否存在。例如: : - isset($json['passengers'])!empty($json['passengers'])

+0

非常感謝。它的工作現在完美:D –