我尝试用php代码解析json变量。问题是一些数组键包含每次迭代的可变值。顺便说一下,这不是一个重复的问题,没有像json解析变量的变量。这是我的json示例和php代码,也是输出;
{
"link":"",
"host":"stream",
"filename":"Rock Ballads The Best Of 70-90's",
"icon":"https:\/\/i.ytimg.com\/vi\/JN80ayCfmW0\/hqdefault.jpg",
"streaming":{
"audio track in mp3 (54.54MB)":"http:\/\/server.example.parsing.com\/str\/wlqcjv8246\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28p%29.mp3",
"360p video in mp4 (80.04MB)":"http:\/\/server.example.parsing.com\/str\/wlqcjyfc33\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28480p%29.mp4",
"240p video in mp4 (76.55MB)":"http:\/\/server.example.parsing.com\/str\/wlqck18b72\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28240p%29.mp4",
"144p video in mp4 (71.09MB)":"http:\/\/server.example.parsing.com\/str\/wlqck4e410\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28144p%29.mp4"
},
"nb":0,
"error":"",
"paws":false
}
这是我使用的php代码;
if($host=="www.youtube.com"){
$decodeProcess = json_decode($output,true);
echo ($decodeProcess['filename']);
echo ($decodeProcess['icon']);
echo ($decodeProcess['streaming']['audio track in mp3 (54.54MB)']);
}
在这种情况下,文件名和图标效果很好,但"音频曲目在mp3(54.54MB)"或" 144p视频在mp4(71.09MB)"我解析是有问题的,因为每次文件大小都会改变。我能做什么?
答案 0 :(得分:0)
您是否考虑在数据结构上运行简单的映射操作以使其更加可行(基本上从键中删除文件大小信息)?
这可能看起来像:
if($host=="www.youtube.com"){
$decodeProcess = json_decode($output,true);
// array of prefix matches that will be used as as substitution keys
$key_replacements = [
'audio' => 'audio',
'360p video' => 'video_360p',
'240p video' => 'video_240p',
'144p video' => 'video_144p'
];
foreach($decodeProcess['streaming'] as $key => $value) {
foreach ($key_replacements as $prefix => $replacement) {
if (strpos($key, $prefix) === 0) {
$decodeProcess['streaming'][$replacement] = $value;
break;
}
}
unset($decodeProces['streaming'][$key]);
}
echo ($decodeProcess['filename']);
echo ($decodeProcess['icon']);
echo ($decodeProcess['streaming']['audio']);
echo ($decodeProcess['streaming']['video_360p']);
}
当然,您可能希望将整个JSON反序列化和键映射功能封装到自己的函数或类方法中。