php – 显示一系列天数

前端之家收集整理的这篇文章主要介绍了php – 显示一系列天数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有这些数字数组,对应于一周中的天数(从星期一开始):
/* Monday - Sunday */
array(1,2,3,4,5,6,7)

/* Wednesday */
array(3)

/* Monday - Wednesday and Sunday */
array(1,7)

/* Monday - Wednesday,Friday and Sunday */
array(1,7)

/* Monday - Wednesday and Friday - Sunday */
array(1,7)

/* Wednesday and Sunday */
array(3,7)

如何有效地将这些数组转换为所需的字符串,如C风格的注释所示?任何帮助将不胜感激.

以下代码应该工作:
<?PHP
// Create a function which will take the array as its argument
function describe_days($arr){
$days = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
// Begin with a blank string and keep adding data to it
$str = "";
// Loop through the values of the array but the keys will be important as well
foreach($arr as $key => $val){
// If it’s the first element of the array or ...
// an element which is not exactly 1 greater than its prevIoUs element ...
    if($key == 0 || $val != $arr[$key-1]+1){
        $str .= $days[$val-1]."-";
    }
// If it’s the last element of the array or ...
// an element which is not exactly 1 less than its next element ...
    if($key == sizeof($arr)-1){
        $str .= $days[$val-1];
    }
    else if($arr[$key+1] != $val+1){
        $str .= $days[$val-1]." and ";
    }
}
// Correct instances of repetition,if any
$str = preg_replace("/([A-Z][a-z]+)-\\1/","\\1",$str);
// Replace all the "and"s with commas,except for the last one
$str = preg_replace("/ and/",",$str,substr_count($str," and")-1);
return $str;
}

var_dump(describe_days(array(4,6)));      // Thursday-Saturday
var_dump(describe_days(array(2,7)));   // Tuesday-Thursday and Sunday
var_dump(describe_days(array(3,6)));         // Wednesday and Saturday
var_dump(describe_days(array(1,6)));   // Monday,Wednesday and Friday-Saturday
?>
原文链接:https://www.f2er.com/php/134185.html

猜你在找的PHP相关文章