[英]How to parse Soundcloud json response using PHP
Its only getting throught the track values.它只能通过轨道值。 What I need is to get the username.我需要的是获取用户名。 Here is what Im usign, thanks这是我使用的,谢谢
{ "items":[ { "kind":"track", "id":33369455, "uri":"https://api.soundcloud.com/tracks/33369455", "user":{ "id":758840, "username":"JoeDreamer", "avatar_url":"https://i1.sndcdn.com/avatars-000006878204-maqsrd-large.jpg?923db0b"}, "download_count":0, "comment_count":1 }, { "kind":"track", "id":33369455, "uri":"https://api.soundcloud.com/tracks/33369455", "user":{ "id":758840, "username":"JoeDreamer", "avatar_url":"https://i1.sndcdn.com/avatars-000006878204-maqsrd-large.jpg?923db0b"}, "download_count":0, "comment_count":1 }] }
$user = json_decode(file_get_contents("http://mydata.com/data.json")); foreach($user->items as $mydata) { echo $mydata->id . "\n"; foreach($mydata->user as $value) { echo $value->username . "\n"; } }
maybe也许
$user = json_decode(file_get_contents("http://mydata.com/data.json"));
foreach($user->items as $mydata)
{
echo $mydata->id . "\n";
echo $mydata->user->username;
}
By adding an additional flag to the json_decode()
function, we can tell the function to return an associative array instead of objects.通过向json_decode()
函数添加一个额外的标志,我们可以告诉函数返回一个关联数组而不是对象。
json_decode ( string $json [, bool $assoc = false ]) json_decode ( 字符串 $json [, bool $assoc = false ])
If you elect to use json_decode
like this, your tasks becomes quite a lot simpler.如果您选择像这样使用json_decode
,您的任务会变得非常简单。 You can access the username as if you were accessing a multidimensional array.您可以像访问多维数组一样访问用户名。
$user = json_decode($str,true); // notice the "true" argument here
foreach($user['items'] as $mydata)
{
echo $mydata['id'] . "," . $mydata['user']['username'] . "\n";
}
What you might have missed is that $myData-user
is an object within itself.您可能错过的是$myData-user
本身就是一个对象。 PHP's json_decode() function works recursively passing over every element of the JSON string you use. PHP 的json_decode()函数以递归方式传递您使用的 JSON 字符串的每个元素。
{
"kind":"track",
...
"user":{
"id":758840,
"username":"JoeDreamer",
...
}
}
You'll have to access the username as a property of it's parent element.您必须访问用户名作为其父元素的属性。 By adding the additional key
variable to the inner foreach
loop, we can inspect the key name and only select the username
property.通过向内部foreach
循环添加额外的key
变量,我们可以检查键名并只选择username
属性。
...
foreach($mydata->user as $key=>$value){
if ($key == 'username'){
echo $value . "\n";
}
}
The additional loop however, is redundant.然而,额外的循环是多余的。 Unless you have some certain specific need to loop over every one of the properties, you could simply access the username directly like this -除非您有某些特定的需要遍历每个属性,否则您可以像这样直接访问用户名 -
$mydata->user->username
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.