PHP JSON解析(数字属性?) [英] PHP JSON parsing (number attributes?)
问题描述
我有一个像这样的JSON字符串:
Hi i have a JSON string like this:
{
"vidID": "CevxZvSJLk8",
"vidTitle": "Katy Perry - Roar (Official)",
"vidInfo": {
"0": {
"rSize": "67.79 MB",
"quality": "720",
"directurl": "https://r2---sn-5uh5o-f5f6.googlevideo.com/videoplayback?ipbits=0&mm=31&mn=sn-5uh5o-f5f6&itag=22&mt=1492837642&dur=269.165&id=o-AB1T_kZWIIiA_ihhSlAK4RXegp3Z9A18zn39hF0Aa51G&initcwndbps=197500&pl=21&source=youtube&mv=m&ip=137.74.1.176&mime=video%2Fmp4&ms=au&ratebypass=yes&requiressl=yes&sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&key=yt6&lmt=1478841669593636&upn=Wp652d9rFKo&ei=OuX6WLqMDJaLNK-MmLAE&expire=1492859290&signature=A8B328D48101C553D0659D2D9D1F1B2F249D2035.792897E2CF6BFEFC97C81A90EA9CBF9B76FD0283&type=video%252Fmp4%253B%2Bcodecs%253D%2522avc1.64001F%252C%2Bmp4a.40.2%2522&quality=hd720&title=Katy%2BPerry%2B-%2BRoar%2B%2528Official%2529",
"dloadUrl": "//downloadmp.org/@download/22-58fae53acfc14-mp4-71087585/videos/CevxZvSJLk8/Katy%2BPerry%2B-%2BRoar%2B%2528Official%2529.mp4",
"ftype": "mp4",
"framerate": "",
"bitrate": "",
"codec": "",
"itag": "22",
"vidid": "CevxZvSJLk8"
}}}
我正在尝试获取直接url的价值. 这是我的PHP代码:
And i am trying to get value of direct url. So here is my PHP code:
$obj = json_decode($json);
echo $obj->vidInfo[0]->directurl;
也尝试过
echo $obj->vidInfo->0->directurl;
但是我无法获得属性直接url的值.
but i can't get the value of attribute direct url.
推荐答案
问题是,"0"
不是数字,因此您不能使用常规数组访问.相反,您必须像访问名称一样访问它.但是由于0
不是有效的标识符,因此您必须使用{}
语法.
The problem is, "0"
isn't a number, so you cant use the normal array access. Instead, you have to access it like an name. But as 0
isn't a valid identifier, you have to use the {}
-syntax.
echo $obj->vidInfo->{"0"}->directurl;
解决此问题的另一种方法是将true
作为第二个参数传递给json_decode
.这样做会返回一个assoc数组,而不是对象格式.
The other way to get around this problem would be to pass true
as second param to json_decode
. Doing this would return you an assoc array and not the object format.
$data = json_decode($json, true);
echo $data['vidInfo'][0]['directurl'];
这篇关于PHP JSON解析(数字属性?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!