从 json 获取数据,并仅使用一个结果作为值


Get data from json and use just one result as value

>我正在尝试使用 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; }

你有一个对象,其中包括一个名为standing的对象数组,它们又具有teamName属性。所以要得到第一个你会做的

if($details->standing[0]->teamName == 'Manchester United')

或者,您可以遍历standing并在有多个条目的情况下获取所有条目

喜欢

foreach($details->standing as $record)
{
   if($record->teamName == 'Manchester United')
      $gamesPlayed=$record->playedGames;
}