我在尝试从多级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 />";
}
}
但我得到
第10行的parse.php中的非法字符串偏移'text'
第11行的parse.php中的非法字符串偏移'href'
它只显示
hhRR01 / 13/2016 - 无 - 北美
hhFFhhDD01 / 13/2016 - 无 - 亚洲
我确信我正在做的事情很容易解决,但作为一个菜鸟,我搞砸了。
答案 0 :(得分:1)
您的嵌套循环是不必要的,以及错误原因:
public static class TeamService
{
public static Team GetTeam(string id)
{
using (var Db = new ApplicationDbContext())
{
//TODO:
}
}
}
答案 1 :(得分:0)
无需将完美的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
);
}
}