显示一系列天数

Wil*_*art 8 php date days

假设我有这些数字对应于一周中的天数(从星期一开始):

/* Monday - Sunday */
array(1, 2, 3, 4, 5, 6, 7)

/* Wednesday */
array(3)

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

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

/* Monday - Wednesday and Friday - Sunday */
array(1, 2, 3, 5, 6, 7)

/* Wednesday and Sunday */
array(3, 7)
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*tta 4

以下代码应该可以工作:

\n\n
<?php\n// Create a function which will take the array as its argument\nfunction describe_days($arr){\n$days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");\n// Begin with a blank string and keep adding data to it\n$str = "";\n// Loop through the values of the array but the keys will be important as well\nforeach($arr as $key => $val){\n// If it\xe2\x80\x99s the first element of the array or ...\n// an element which is not exactly 1 greater than its previous element ...\n    if($key == 0 || $val != $arr[$key-1]+1){\n        $str .= $days[$val-1]."-";\n    }\n// If it\xe2\x80\x99s the last element of the array or ...\n// an element which is not exactly 1 less than its next element ...\n    if($key == sizeof($arr)-1){\n        $str .= $days[$val-1];\n    }\n    else if($arr[$key+1] != $val+1){\n        $str .= $days[$val-1]." and ";\n    }\n}\n// Correct instances of repetition, if any\n$str = preg_replace("/([A-Z][a-z]+)-\\\\1/", "\\\\1", $str);\n// Replace all the "and"s with commas, except for the last one\n$str = preg_replace("/ and/", ",", $str, substr_count($str, " and")-1);\nreturn $str;\n}\n\nvar_dump(describe_days(array(4, 5, 6)));      // Thursday-Saturday\nvar_dump(describe_days(array(2, 3, 4, 7)));   // Tuesday-Thursday and Sunday\nvar_dump(describe_days(array(3, 6)));         // Wednesday and Saturday\nvar_dump(describe_days(array(1, 3, 5, 6)));   // Monday, Wednesday and Friday-Saturday\n?>\n
Run Code Online (Sandbox Code Playgroud)\n