如何从API/URL的特定数组中获取指定stream_title的content_stream
问题分析与解决方案
你的代码核心问题在于:找到匹配content_id的频道后,错误地使用了频道循环的索引$i去获取streams->live数组中的流,这导致无论传入的stream_title是什么,都会取到对应索引的流(比如content_id=1时$i=0,固定取SD流)。
修复后的代码
// The result of the request: $json = <<<END_OF_STRING {"live": [{"content_id": "1","title": "Channel 1","country_id": "2","language_id": "6","genre_id": "1","image_url": "","epg": {"daily": "","weekly": ""},"streams": {"live": [{"stream_title": "SD","content_stream": "http://example.com/sd/1","default": "0"}, {"stream_title": "HD","content_stream": "http://example.com/hd/1","default": "1"}, {"stream_title": "FHD","content_stream": "http://example.com/fhd/1","default": "0"}],"dvr": ""}}, {"content_id": "2","title": "Channel 2","country_id": "2","language_id": "6","genre_id": "2","image_url": "","epg": {"daily": "","weekly": ""},"streams": {"live": [{"stream_title": "SD","content_stream": "http://example.com/sd/2","default": "0"}, {"stream_title": "HD","content_stream": "http://example.com/hd/2","default": "1"}, {"stream_title": "FHD","content_stream": "http://example.com/fhd/2","default": "0"}],"dvr": ""}}]} END_OF_STRING; $json_decoded = json_decode($json); $content_id = $_GET['content_id']; $stream_title = $_GET['stream_title']; $desiredLink = ''; // 遍历所有频道 foreach ($json_decoded->live as $channel) { // 匹配目标content_id if ($channel->content_id === $content_id) { // 遍历当前频道的所有直播流 foreach ($channel->streams->live as $stream) { // 匹配指定的stream_title if ($stream->stream_title === $stream_title) { $desiredLink = $stream->content_stream; break; // 找到后退出循环,提升效率 } } break; // 找到目标频道后退出外层循环 } } // 可选:如果未找到指定清晰度,返回默认流(比如HD) if (empty($desiredLink)) { foreach ($json_decoded->live as $channel) { if ($channel->content_id === $content_id) { foreach ($channel->streams->live as $stream) { if ($stream->default === "1") { $desiredLink = $stream->content_stream; break; } } break; } } } echo $desiredLink;
关键修改点
- 改用
foreach遍历频道和流,逻辑更清晰,避免索引混乱 - 找到匹配
content_id的频道后,单独遍历该频道下的所有live流,对比stream_title参数获取对应流地址 - 增加了默认流 fallback 逻辑:如果传入的
stream_title不存在(比如拼写错误),会自动返回标记为default:1的流(即HD)
现在测试链接https://example.com/ch.php?content_id=1&stream_title=HD,会正确返回http://example.com/hd/1;传入stream_title=FHD则返回http://example.com/fhd/1,完全符合需求。
内容的提问来源于stack exchange,提问作者achraf
相关产品推荐
相关产品推荐

