我有以下代码
$day = $_GET['day'];
$month = $_GET['month'];
if($day=='1'&&$month=='January'){
echo "<img src=\"playingCard/spades/13.png\" alt='' />";
} elseif ($day=='2'&&$month=='January'){
echo "<img src=\"playingCard/spades/12.png\" alt='' />";
} elseif ($day=='3'&&$month=='January'||$day=='1'&&$month=='February'){
echo "<img src=\"playingCard/spades/11.png\" alt='' />";
} elseif ($day=='4'&&$month=='January'){
echo "<img src=\"playingCard/spades/10.png\" alt='' />";
} ....
并且有一个表单,您可以在其中输入当天的数字和月份的值。 我想做的是在特定日期显示特定的扑克牌。 例如
January 1st = king of spades
January 2nd = Queen of spades
February 1st = Jack of spades
and so on
我有一个文件夹,其中我保存了4个子文件夹,其中包含4张扑克牌的图片。
到目前为止代码工作正常,但是365天会花费很长时间,是否有一种简单的方法可以用更少的代码来完成?
希望我足够清楚。
提前谢谢。
答案 0 :(得分:3)
我没有方便的PHP解释器,但这应该给你一个大概的想法(或者它可能只是在最小的编辑后才能工作):
$day = $_GET['day'];
$month = $_GET['month'];
$images = array (
"January" => array ( 1 => "path to image", 2 => "path to another image", ... ),
"February" => array ( 1 => "path to image", 2 => "path to another image", ... ),
...
);
echo $images[$month][$day];
$images
变量可以移动到单独的.php
文件中,整个过程看起来就像下面这样(将文件命名为你想要的):
months_initialiser.php:
<?php
$images = array (
"January" => array ( 1 => "path to image", 2 => "path to another image", ... ),
"February" => array ( 1 => "path to image", 2 => "path to another image", ... ),
...
);
?>
您的实际档案:
<?php
$day = $_GET['day'];
$month = $_GET['month'];
include 'months_initialiser.php';
echo $images[$month][$day];
?>
答案 1 :(得分:1)
如果您无法定义应显示哪个卡的常规模式,则可以将图像文件的路径放在366个元素的数组中,然后使用day of the year索引数组。
如果你可以定义一个常规模式,你只需要一个52个元素的数组,然后用$day_of_year % 52
来获取索引。 (这将是用于定义数组的更少代码,但从您的示例来看,它看起来并不像您有常规模式。)
答案 2 :(得分:1)
正如其他人所指出的那样,没有这种模式,很难给出一个完美的答案......但如果你想用一个看似随机但可预测的顺序一遍又一遍地穿过甲板,你可以使用带开关参数的mod(%):
//get numerical day of the year
$dayofyear = date('z', mktime(12, 0, 0, $month, $day, date('Y')));
$suit = '';
//will result in 1 on jan-1, 2 on jan-2, up to 13, then back to 1.
$card = ($dayofyear % 13) + 1;
$nSuit = ($dayofyear % 4) + 1;
switch ($nSuit) {
case 1:
$suit = 'spades';
break;
case 2:
$suit = 'hearts';
break;
case 3:
$suit = 'clubs';
break;
case 4:
$suit = 'diamonds';
break;
}
echo "<img src=\"playingCard/" . $suit . "/" . $card . ".png\" alt='' />";
这将导致
spades 1
hearts 2
clubs 3
diamonds 4
spades 5
hearts 6
clubs 7
diamonds 8
spades 9
hearts 10
clubs 11
diamonds 12
spades 13
hearts 1
clubs 2
diamonds 3