PHP遍历播放列表数组返回无效响应,next字段为null问题求助
问题原因
两个问题的根源是同一个,就是没有处理遍历到数组末尾的边界情况:
你用来查找第一条开播时间晚于当前时间的for循环,当所有条目的开播时间都早于当前时间时(比如你测试时的时间晚于最后一条的19:12:26),循环会执行完所有9次迭代,最终$i的值为9,等于count($playData)的结果,已经超出了数组的最大有效索引8。此时直接访问$playData[$i]就会返回空值,序号也自然变成了超出边界的9。
额外补充:你当前的逻辑还有一个隐藏问题:如果当前时间早于第一条节目的开播时间,循环第一次判断就会触发break,此时$i=0,访问$playData[$i-1]也就是$playData[-1]也会出现越界错误。
修复代码
public function getPlayingItem() { $playData = []; $startTimes = []; for($i=0; $i < count($this->playListFiles); $i++){ $item = $this->playListFiles[$i]; if(empty($item)){ unset($this->playListFiles[$i]); continue; } $tmp = explode(',', $item); $playData[$i]['startTime'] = array_pop($tmp); $startTimes[$i] = $playData[$i]['startTime']; $playData[$i]['name'] = implode(',',$tmp); } array_multisort($startTimes, SORT_ASC, $playData); $total = count($playData); $i = 0; // 遍历找第一条晚于当前时间的条目 for(; $i < $total; $i++){ if (strtotime($playData[$i]['startTime']) >= time()){ break; } } $playing = []; $next = []; // 处理当前播放条目 if ($i == 0) { // 当前时间比所有节目都早,当前播放为最后一条(或按需调整为无播放) $playingIndex = $total - 1; } else { $playingIndex = $i - 1; } $info = $this->get_mp3($playData[$playingIndex]['name'], true, false); $tmp = explode(DS,$playData[$playingIndex]['name']); $name = array_pop($tmp); $playing = [ 'number' => $playingIndex, 'path' => $playData[$playingIndex]['name'], 'name' => $name, 'duration' => $info['data']['time'], 'startTime' => $playData[$playingIndex]['startTime'] ]; // 处理下一条目 if ($i < $total) { // 有下一条 $nextIndex = $i; $info = $this->get_mp3($playData[$nextIndex]['name'], true, false); $tmp = explode(DS,$playData[$nextIndex]['name']); $name = array_pop($tmp); $next = [ 'number' => $nextIndex, 'path' => $playData[$nextIndex]['name'], 'name' => $name, 'duration' => $info['data']['time'], 'startTime' => $playData[$nextIndex]['startTime'] ]; } else { // 没有下一条,可按需调整为循环取第一条作为次日播放 $next = [ 'number' => null, 'path' => null, 'name' => '今日节目已全部播放完毕', 'duration' => null, 'startTime' => null ]; } $output = ['playing' => $playing, 'next' => $next]; return $output; }
修改说明
- 提前计算播放列表总长度
$total,避免重复调用count()影响性能 - 新增了「当前时间早于所有节目开播时间」的场景处理,避免
$i=0时访问$i-1越界 - 新增下一条的存在性判断,只有
$i小于总长度时才读取下一条的信息,不会再出现越界问题 - 没有下一条时返回明确的提示,你也可以根据业务需求修改为循环读取第一天的节目作为下一条。
内容的提问来源于stack exchange,提问作者irfan khan
相关产品推荐
相关产品推荐

