我过去与php一起使用数组,但通常简单的关联数组,易于管理和爬网。
我正在向API端点提出HTTP POST请求,该请求以JSON格式返回大量数据。我正在使用JSON_DECODE($ wendest,true)将JSON转换为数组,并且正在尝试访问数组的组件而无需运气 - 只需为我服务一个空白页即可。另外,如果我在数组上执行print_r,我只会得到一个数据,所以我至少知道API正在返回数据。
这是API
响应的片段{
"data": {
"accounts": [
{
"locations": [
{
"name": "Test Location",
"soundZones": [
{
"name": "Main",
"nowPlaying": {
"startedAt": "2017-09-06T00:38:51.000Z",
"track": {
"name": "Some Song Name 123",
"imageUrl": "https://some-cdn-url.com",
"Uri": "5hXEcqQhEjfZdbIZLO8mf2",
"durationMs": 327000,
"artists": [
{
"name": "SomeName",
"Uri": "5lpH0xAS4fVfLkACg9DAuM"
}
]
}
}
}
]
},
我如何使用PHP访问轨道对象下的名称值?(在此示例中,我将尝试返回"某些歌曲名称123"的值)
这是我正在使用的代码..我知道我离我们不在
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$response = json_decode($response, true);
print_r($response[0]);
那是因为您不仅要返回数组,而且还归还一个数组和对象。
<?php
echo $response[0]->data->accounts[0]['locations'][0]->soundZones[0]->nowPlaying->track->name;
我更喜欢sf_admin的答案,因为这种混乱的对象确实使自己更适合成为一个对象,但是使用json_decode($response, true)
,我认为您应该能够这样访问它:
echo $response[0]['data']['accounts'][0]['locations'][0]['soundZones'][0][0]['nowPlaying']['track']['name'];
尝试这个。
//$response = json_decode($response, true);
$response = json_decode($response);
// loop
if (isset($response->data->accounts)) {
foreach ($response->data->accounts as $account) {
foreach ($account->locations as $location) {
foreach ($location->soundZones as $soundZone) {
print_r($soundZone->nowPlaying->track->name);
}
}
}
}
// first
if (isset($response->data->accounts[0]->locations[0]->soundZones[0]->nowPlaying->track->name)) {
print_r($response->data->accounts[0]->locations[0]->soundZones[0]->nowPlaying->track->name);
}
一些歌曲名称123