我试图使用www.football-data.org获得足球联赛积分榜,但我之前从未使用过JSON。
目前我正在使用以下内容:
$uri = 'http://api.football-data.org/v1/soccerseasons/398/leagueTable/';
$reqPrefs['http']['method'] = 'GET';
$reqPrefs['http']['header'] = 'X-Auth-Token:'.$api_key;
$stream_context = stream_context_create($reqPrefs);
$response = file_get_contents($uri, false, $stream_context);
$details = json_decode($response);
尝试获取一个团队的详细信息。目前我正在使用:
echo "<pre>";
print_r($details);
echo "</pre>";
获取以下内容:
stdClass Object
(
[_links] => stdClass Object
(
[self] => stdClass Object
(
[href] => http://api.football-data.org/v1/soccerseasons/398/leagueTable/?matchday=26
)
[soccerseason] => stdClass Object
(
[href] => http://api.football-data.org/v1/soccerseasons/398
)
)
[leagueCaption] => Premier League 2015/16
[matchday] => 26
[standing] => Array
(
[0] => stdClass Object
(
[_links] => stdClass Object
(
[team] => stdClass Object
(
[href] => http://api.football-data.org/v1/teams/338
)
)
[position] => 1
[teamName] => Leicester City FC
[crestURI] => http://upload.wikimedia.org/wikipedia/en/6/63/Leicester02.png
[playedGames] => 25
[points] => 53
[goals] => 47
[goalsAgainst] => 27
[goalDifference] => 20
[wins] => 15
[draws] => 8
[losses] => 2
[home] => stdClass Object
(
[goals] => 21
[goalsAgainst] => 13
[wins] => 7
[draws] => 4
[losses] => 1
)
[away] => stdClass Object
(
[goals] => 26
[goalsAgainst] => 14
[wins] => 8
[draws] => 4
[losses] => 1
)
)
首先,我如何获取这些值并将它们保存为PHP中的可用变量?
其次,是否可以将这些数据缩小到一个团队?比如说:
if($details->teamName == 'Manchester United') { $gamesPlayed = $details->gamesPlayed; }
答案 0 :(得分:2)
你有一个Object,其中包含一个名为standing
的对象数组,而它们又具有teamName
属性。所以要获得你要做的第一个
if($details->standing[0]->teamName == 'Manchester United')
或者,如果有多个条目,您可以循环遍历standing
并获取所有条目
像
foreach($details->standing as $record)
{
if($record->teamName == 'Manchester United')
$gamesPlayed=$record->playedGames;
}