You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定优先级从视频画质数组中选择符合要求的画质?

Solution for Prioritizing Video Quality Selection

Problem with Original Code

Your original code iterates through the available qualities array in its given order, checking each entry against priority criteria. Since the array can be unordered, this might select a lower-priority quality if it appears earlier in the list. For example, if 720p comes before 480p in the array, the code would pick 720p even though 480p has higher priority.

Corrected Approach

Instead of looping through the available qualities, iterate through your priority rules from highest to lowest. For each rule, check if there's a matching quality in the available list. Once a match is found, select it immediately to ensure priority is respected.

Corrected Code

$quality = [
    "720p",
    "480p",
    "hls-5999",
    "hls-666"
];

$selectedQuality = null;

// Check highest priority: 480p
if (in_array("480p", $quality)) {
    $selectedQuality = "480p";
}
// Next priority: 720p
elseif (in_array("720p", $quality)) {
    $selectedQuality = "720p";
}
// Next priority: SD
elseif (in_array("SD", $quality)) {
    $selectedQuality = "SD";
}
// Next priority: hls-5xxx (regex match)
else {
    foreach ($quality as $q) {
        if (preg_match('/hls-5\d{3}/', $q)) {
            $selectedQuality = $q;
            break;
        }
    }
}

// Fallback if no matching quality found
if ($selectedQuality === null) {
    $selectedQuality = $quality[0] ?? null; // Pick first available or set to null
}

// Output the result
echo $selectedQuality; // Returns "480p" for the example array

How This Works

  • We check each priority level in order, starting with the highest (480p).
  • For exact match rules, in_array() quickly verifies if the quality exists in the available list.
  • For the regex rule, we loop through the qualities to find the first match that fits hls-5\d{3}.
  • A fallback ensures we have a value even if no rules are matched.

Content of the question originates from Stack Exchange, question author Alireza Ysh.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:05:04