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
?>

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...