Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:如何将以逗号分隔的等级字符串转换为英语可读的;等级范围;?_Php_Regex_Csv_Explode - Fatal编程技术网

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

PHP:如何将以逗号分隔的等级字符串转换为英语可读的;等级范围;?,php,regex,csv,explode,Php,Regex,Csv,Explode,我有一个学生等级的字符串(不是数组)。以下是一些可能的条目示例: 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 t

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

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;
    }


?>

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

谢谢!我同意,这封信把它扔掉了。首先,我可能必须改变数据进入的方式,以便稍微清理一下。我需要在代码中再添加一条if语句,以便在级别仅为1级时捕获。我在所有其他ifs之前添加了它:if($lastItem==$firstItem){$output=$firstItem;return$output;}现在考虑一下,您只需在处理过程中将K设为0,然后使用str_replace(“0”,“K”,“$output”)在输出上更改它。无论如何,我现在在帖子中做了这些更改,尽管方式不同。是的,我只是对0有同样的想法。