json 中的未定义偏移量 0 php 中的值
Undefined offset 0 in json value in php
我正在尝试将这条铁路 api 用于我的项目。如果我输入一个正确的数字,那么它就可以正常工作,但是如果我输入一个随机的 10 位数字,那么我会在第 20 行和第 21 行收到未定义的 offset:0 错误。我是新手,我已经搜索了很多解决方案但找不到。
<?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 [Naveen@javadomain.in]";
}
$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'];
?>
使用var_export
或print_r
函数检查$json['passengers']
中到底存储了什么
可能 json 值具有不同的结构。
编辑:
可能是由于输入错误,json您得到的回复结构不同。所以您可以先检查它,然后使用 if else 条件来查看该特定数组元素是否存在。
例如:- isset($json['passengers'])
或 !empty($json['passengers'])
我正在尝试将这条铁路 api 用于我的项目。如果我输入一个正确的数字,那么它就可以正常工作,但是如果我输入一个随机的 10 位数字,那么我会在第 20 行和第 21 行收到未定义的 offset:0 错误。我是新手,我已经搜索了很多解决方案但找不到。
<?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 [Naveen@javadomain.in]";
}
$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'];
?>
使用var_export
或print_r
函数检查$json['passengers']
可能 json 值具有不同的结构。
编辑:
可能是由于输入错误,json您得到的回复结构不同。所以您可以先检查它,然后使用 if else 条件来查看该特定数组元素是否存在。
例如:- isset($json['passengers'])
或 !empty($json['passengers'])