我在尝试从多级 json url 中提取一些数据时遇到了一些问题。我可以得到除某个嵌套部分之外的其他所有内容。
{
"name": "NewNationsPnW",
"count": 10,
"frequency": "Every 15 mins",
"version": 31,
"newdata": false,
"lastrunstatus": "success",
"thisversionstatus": "success",
"nextrun": "Wed Jan 13 2016 22:57:30 GMT+0000 (UTC)",
"thisversionrun": "Wed Jan 13 2016 22:42:30 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"Nation": {
"href": "https://politicsandwar.com/nation/id=30953",
"text": "Renegade States"
},
"Founded": "01/13/2016",
"Alliance": "None",
"Continent": "North America",
"property7": "",
"index": 1,
"url": "https://politicsandwar.com/nations/"
}
]
}
}
以下代码用于显示该嵌套区域,但我想将其用于各个输出。
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$json = json_decode($response, true);
//echo '<pre>'; print_r($results);
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1;
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
我尝试了以下方法
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1['text'];
echo $stat1['href'];
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
但我得到
解析中的非法字符串偏移"文本".php在第 10 行
解析中的非法字符串偏移量"href".php在第 11 行
以及它只显示
hhRR01/13/2016 - 无 - 北美
hhFFhhDD01/13/2016 - 无 - 亚洲
我确信我正在做一些简单修复的事情,但作为一个菜鸟,我把一切都搞砸了。
你的嵌套循环是不必要的,错误的原因:
foreach($json['results']['collection1'] as $stat) {
echo $stat['nation']['text'];
echo $stat['nation']['href'];
}
没有必要将一个完美的JSON对象数据结构转换为数组。
<?php
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$j = json_decode($response );
foreach ($j->results->collection1 as $collection1 ) {
echo $collection1->Nation->href;
echo $collection1->Nation->text;
if($collection1->Alliance == 'None') {
echo sprintf("%s - %s - %s<br />",
$collection1->Founded,
$collection1->Alliance,
$collection1->Continent
);
}
}