通过编写更少的代码来做同样的事情

问题描述 投票:0回答:3

我有以下代码

$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天会花费很长时间,是否有一种简单的方法可以用更少的代码来完成它?

希望我足够清楚。

先感谢您。

php forms display
3个回答
1
投票

正如其他人所指出的那样,没有这种模式,很难给出一个完美的答案......但是如果你想用一个看似随机但可预测的顺序一遍又一遍地穿过套牌,你可以使用mod(%)和一个开关statment:

//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

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
投票

如果无法定义应显示哪个卡的常规模式,则可以将图像文件的路径放在366元素数组中,然后使用day of the year索引数组。

如果您可以定义常规模式,则只需要一个52个元素的数组,然后使用$day_of_year % 52来获取索引。 (这将是定义数组的代码少得多,但从您的示例来看,它看起来并不像您有一个常规模式。)

© www.soinside.com 2019 - 2024. All rights reserved.