PHP:如何将等级级别的逗号分隔字符串转换为英语可读的“”;等级范围”;


PHP: How to convert comma separated strings of grade levels to english-readable "grade ranges"?

我有一个学生等级的字符串(而不是数组)。以下是一些可能的条目示例:

k,1,2,3,4,5
1,2,3,4
1
1,2
3,4,5

学生的最高成绩是5分。

我想把字符串转换成英语可读范围。因此,在我上面的例子中,这将是输出:

K & Up
1-4
1
1 & 2
3 & Up

如何最好地处理此问题?示例不胜感激,谢谢!

<?php
function toRange($string)
{
$min = "K";
$max = 5;
//take string and turn into an array
$grades = explode(", ",$string);
$firstItem = $grades[0];
$lastItem = $grades[count($grades)-1];
if (count($grades) == 1)
{
  $output = $firstItem;
}
else
{
    if ($firstItem == "K")
    {
        if ($lastItem == 5)
        {
          $output = "K & Up";
        }
        if ($lastItem == 1)
        {
            $output = "K & 1";
        }
        else {
            $output = "K -" . $lastItem;
        }
        break;
    }
    else 
    {
        if ($lastItem == 5)
        {
            if ($firstItem != 4)
            {
                $output = $firstItem . " & Up";
            }
            else {
                $output = "4 & 5";
            }
        }
        else {
            if ($lastItem > $firstItem + 1)
            {
                $output = $firstItem . " - " . $lastItem;
            }
            else {
                $output = $firstItem . " & " . $lastItem;
            }
        }
    }

     }
return $output;
    }

?>

如果不是这封信的参与,这本可以容易得多。