我有如下代码。我正在阅读一个 JSON URL 并用一些 if 条件回显一些项目。我需要以 JSON 格式重新回显所选项目。
<?php
// Array of trains to list
//Arrival train list
$trainNumbers = array(
9021,11077
);
$json = file_get_contents('myURL.json');
$trainData = json_decode($json, true);
foreach ($trainData[0] as $train) {
$trainNumber = $train[0][0];
if (in_array($trainNumber, $trainNumbers)) {
$fields = array(
'train_no',
'train_name',
'dep_date',
'dep_station',
'dep_log',
'dep_lat',
'arr_station',
'delay_time',
'new_lat',
'new_long',
'new_station',
'new_station_name',
'time_delay',
'station_left'
);
foreach ($train[0] as $i => $dataField) {
echo $fields[$i] . " - {$dataField}\n";
$trains[$trainNumber][$fields[$i]] = $datafield;
}
echo "\n";
}
}
?>
上面的代码显示数据如
train_no - 09021
train_name - MUMBAI BANDRA T - JAMMU TAWI Exp (SPL)
dep_date - 2013-05-06
dep_station - BRSQ
dep_log - 28.613196
dep_lat - 77.14046
arr_station - BRAR SQUARE
delay_time - 150
new_lat - 28.659977
new_long - 77.156425
new_station - UMB
new_station_name - AMBALA CANT JN
time_delay - 48
station_left - 67
train_no - 11077
train_name - PUNE - JAMMU TAWI Jhelum Express
dep_date - 2013-05-06
dep_station - HET
dep_log - 26.611628
dep_lat - 77.943449
arr_station - HETAMPUR
delay_time - 56
new_lat - 26.697312
new_long - 77.905769
new_station - DHO
new_station_name - DHAULPUR
time_delay - 44
station_left - 93
如何以 JSON 格式再次回显输出?
按照以下建议进行编辑
$data[$fields[$i]]= " - {$dataField}\n";
echo json_encode($data);
我收到此错误
这是 JSON 输出
实际上,在这个脚本中,我们有 100 列火车的列表,所以我从中调用了一些火车。