我正在尝试解码 JSON 文件。
JSON 的摘录如下所示。为了更准确地描述这个 JSON,它是 3 X 组 JSON 代码。我正在尝试从第一行中提取与“main_train_uid”和“assoc_train_uid”相关的值,例如 G90491 和 G90525。
我一直在尝试复制 stackoverflow 各个部分中显示的代码示例,但失败了
我意识到这应该相对容易,但我就是无法理解。我得到的输出是Json 解码失败并出现错误:0。这表明没有错,但我没有得到这些值。我一直对数组和对象感到困惑。我的代码显示在 JSON 提取之后。
{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"G90491","assoc_train_uid":"G90525","assoc_start_date":"2013-09-07T00:00:00Z","location":"EDINBUR","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"O"}}
{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"P20328","assoc_train_uid":"P21318","assoc_start_date":"2013-08-23T00:00:00Z","location":"MARYLBN","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"C"}}
{"JsonAssociationV1":{"transaction_type":"Delete","main_train_uid":"L13077","assoc_train_uid":"L13045","assoc_start_date":"2013-08-23T00:00:00Z","location":"STPANCI","base_location_suffix":null,"diagram_type":"T","CIF_stp_indicator":"C"}}
JSON 片段存储在 json.txt
<?php
$file = "json.txt";
$trains = file_get_contents($file);
foreach (explode("\n", $trains) as $line) {
$train = json_decode($line,true);
if (is_array($train)) {
foreach($train as $item=>$value) {
foreach($value as $entry) {
echo $entry->main_train_uid;
echo $entry->assoc_train_uid;
}
}
}
}
if (is_null($json_train)) {
die("Json decoding failed with error: ". json_last_error());
}
?>
感谢期待约翰
编辑
感谢巴尔玛
我的新代码如下
<?php
$file = "json.txt";
$trains = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($trains as $train) {
$json=json_decode($train,true);
foreach($json as $item=>$value) {
print_r($item);
foreach($value as $entry) {
echo '<br>';
print_r($entry);
}
}
}
if (is_null($json)) {
die("Json decoding failed with error: ". json_last_error());
}
?>
我现在得到以下输出(即值),没有错误,这很好
JsonAssociationV1
Delete
G90491
G90525
2013-09-07T00:00:00Z
EDINBUR
T
OJsonAssociationV1
Delete
P20328
P21318
2013-08-23T00:00:00Z
MARYLBN
T
CJsonAssociationV1
Delete
L13077
L13045
2013-08-23T00:00:00Z
STPANCI
T
C
但是,我仍然无法挑选出某些单独的值来自行回显(我需要这样做以便稍后将它们放入数据库中)。因此,例如,我仍然无法仅显示main_train_uid的值
此外,因为其中一个值是 NULL,它似乎将某些值推入下一组 JSON。例如上面输出中显示的 T 和 C
任何进一步的帮助表示赞赏
谢谢