php 根据星期几包含文件 - 简洁的代码?

php include file based on day of the week - concise code?

我已经使用之前关于堆栈溢出的一些问题的答案(感谢大家)提出了一个关联数组,其中包含基于星期几的特定文件,但我想知道是否有当路径名看起来很长且重复时,如何使代码更简洁?

$今天=日期("l");

$内容=数组(

"Sunday" => "/home/josull05/htdocs/wdd4/php/main-content/sundays-activities-home.php", "Monday" => "/home/josull05/htdocs/wdd4/php/main-content/mondays-activities-home.php", "Tuesday" => "/home/josull05/htdocs/wdd4/php/main-content/thursdays-activities-home.php", "Wednesday" => "/home/josull05/htdocs/wdd4/php/main-content/wednesdays-activities-home.php", "Thursday" => "/home/josull05/htdocs/wdd4/php/main-content/thursdays-activities-home.php", "Friday" => "/home/josull05/htdocs/wdd4/php/main-content/fridays-activities-home.php", "Saturday" => "/home/josull05/htdocs/wdd4/php/main-content/saturdays-activities-home.php"

); 包括 $content[$today];

您可以尝试以下代码段。

$today = date( 'l' );
$file = '/home/josull05/htdocs/wdd4/php/main-content/' . strtolower( $today ) . 's-activities-home.php';
include( $file );

变量 $today 将获得像 SundayMonday 这样的日期名称。在文件名中我们需要小写日期名称,所以使用strtolower

注意:在包含之前检查文件是否存在是安全的。您可以使用 file_exists.