问题描述
|
我有一个针对学生的年级字符串(不是数组)。以下是一些可能的条目的示例:
k,1,2,3,4,5
1,4
1
1,2
3,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;
}
?>
如果没有这封信的参与,这本来可以容易得多。