从 API json 响应访问数据。阵列? Laravel

Accessing data from API json response. Arrays? Laravel

我正在尝试访问 json 响应 return 中的 steamid 数据,由 API,特别是 Steam API。

响应如下所示:

我做到了 return json 但为什么我到处都看到 array

我将如何访问 steamid 数据?我有点困惑,因为我认为这会是 json.

我正在使用 guzzle 获取数据并使用 guzzle json() 方法将其转换为 json:

如有任何帮助,我们将不胜感激。

谢谢!

API 确实使用 JSON 到 send/receive ,但是 JSON 只是一个字符串,所以为了使用该数据 PHP 必须解析它,这是由 guzzle 自动处理的,因此一旦您取回数据,它就会自动将数据解码为您可以使用的格式。

它使用 json_encode()json_decode() 函数执行此操作。

您可以通过以下方式访问 steamid

// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);

foreach($players as $player)
{
    $steamId = array_get($player, 'steamid', null);
}

使用 laravel 帮助程序 array_get() 函数是确保您 return 在数据不存在时使用合理的默认值以及消除继续执行操作的需要的好方法isset() 之类的东西,以避免有关未定义索引等的错误。 http://laravel.com/docs/5.1/helpers

或者不使用 laravel 助手,你可以使用类似于下面的东西,尽管我建议你添加检查以避免上述问题。

foreach($data['response']['players'] as $player)
{
    $steamId = $player['steamid'];
}

如果您不希望 guzzle 自动解码 API 的 JSON 我相信您应该能够调用 getBody() 方法到 return JSON 字符串。

$json = $response->getBody();