php – 显示一系列天数
发布时间:2020-12-13 17:58:39 所属栏目: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
假设我有这些数字数组,对应于一周中的天数(从星期一开始):
/* 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 ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |