微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/php/134185.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐