你能给我一些如何从这个文件中获取数据的建议吗?
我需要接收一个停靠点和行列表,或者来自最嵌套对象的其他数据,但我现在不知道如何使用JSON中的嵌套对象。
{
"stops": {
"11": "Winna-Karpacka",
"21": "Piwna",
"31": "RondoTysiąclecia",
"41": "Piątkowicka-Wiączyńska",
"51": "Taczańska",
"61": "Komarzewska",
"12": "Winna-Działki",
"22": "Piwna-Karpacka",
"32": "RondoTysiąclecia",
"42": "Piątkowicka",
"52": "Taczańska",
"62": "Komarzewska-Wiączyńska"
},
"lines": {
"1": {
"variants": {
"16": [{
"11": 0
}, {
"21": 3
}, {
"31": 5
}, {
"41": 10
}, {
"51": 12
}, {
"61": 16
}],
"61": [{
"62": 0
}, {
"52": 3
}, {
"42": 6
}, {
"32": 8
}, {
"22": 14
}, {
"12": 16
}]
},
"departures": {
"16": [
"04:00",
"04:50",
"05:40",
"06:30",
"07:20",
"08:10",
"09:00",
"10:00",
"11:00",
"12:00",
"13:00",
"14:00",
"14:50",
"15:40",
"16:30",
"17:20",
"18:10",
"19:00",
"20:00",
"21:00",
"22:00"
],
"61": [
"04:25",
"05:15",
"06:05",
"06:55",
"07:45",
"08:35",
"09:30",
"10:30",
"11:30",
"12:30",
"13:30",
"14:25",
"15:15",
"16:05",
"16:55",
"17:45",
"18:35",
"19:30",
"20:30",
"21:30"
]
}
},
"2": {
"variants": {
"25": [{
"21": 0
}, {
"31": 2
}, {
"41": 7
}, {
"51": 9
}],
"52": [{
"52": 0
}, {
"42": 3
}, {
"32": 5
}, {
"22": 11
}]
},
"departures": {
"25": [
"10:15",
"10:45",
"11:15",
"11:45",
"12:15",
"12:45",
"13:15",
"13:45",
"14:15",
"14:45",
"15:15",
"15:45",
"16:15",
"16:45",
"17:15",
"17:45"
],
"52": [
"10:30",
"11:00",
"11:30",
"12:00",
"12:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30",
"17:00",
"17:30"
]
}
},
"3": {
"variants": {
"35": [{
"31": 0
}, {
"41": 12
}, {
"51": 22
}],
"53": [{
"51": 0
}, {
"41": 10
}, {
"31": 22
}]
},
"departures": {
"34": [
"01:10",
"02:10",
"03:10"
],
"43": [
"01:40",
"02:40",
"03:40"
]
}
}
}
}
我尝试过类似的东西,但它不起作用
$str = file_get_contents('dane.json');
$json = json_decode($str, true);
echo $json['stops']['11'];
答案 0 :(得分:0)
json_decode
,然后使用我编写的这个函数生成适当的PHP代码来访问JSON中的任何特定元素。
function jsonGeneratePhp($json, $phpString = '$json') {
if (is_array($json)) {
echo "$phpString<br>";
foreach ($json as $key => $value) {
jsonGeneratePhp($value, "{$phpString}['$key']");
}
} elseif (is_object($json)) {
echo "$phpString<br>";
foreach ($json as $key => $value) {
if (is_numeric($key)) {
jsonGeneratePhp($value, "{$phpString}->{{$key}}");
} else {
jsonGeneratePhp($value, "{$phpString}->$key");
}
}
} else {
echo "$phpString = $json<br>";
}
}
$str = file_get_contents('dane.json');
$json = json_decode($str);
jsonGeneratePhp($json);
这将生成一堆与每条JSON数据相对应的PHP语句,如下所示:
$json
$json->stops
$json->stops->{11} = Winna-Karpacka
$json->stops->{21} = Piwna
...
以= something
结尾的任何内容都是值。
例如:
echo $json->stops->{11}; // Winna-Karpacka
以= something
结尾的任何内容都是您可以使用foreach
进行迭代的数组或对象。
例如:
foreach ($json->stops as $stopId => $stopName) { ... }