PHP循环显示每天的唯一消息

时间:2014-12-01 13:46:59

标签: php loops

我有24天每天都有独特的信息。我怎样才能在某种循环中编写以下IF语句以使其更有效: -

<?

if ($day == '1') {

  $offerTxt = $day1Txt;

} else if ($day == '2') {

  $offerTxt = $day2Txt;

} else if ($day == '3') {

  $offerTxt = $day3Txt;

} else if ($day == '4') {

  $offerTxt = $day4Txt;

} else if ($day == '5') {

  $offerTxt = $day5Txt;

} else if ($day == '6') {

  $offerTxt = $day6Txt;

} 


?>

2 个答案:

答案 0 :(得分:6)

你可以这样内联:

$offerTxt = ${'day'.$day.'Txt'};

您应该检查一天是否在某一组中,所以您的代码看起来与此类似:

$daysUsed = array(1,2,3,4,5,6);
$offerTxt = '';
if(in_array((int)$day, $daysUsed)) {
    $offerTxt = ${'day'.$day.'Txt'};
}

答案 1 :(得分:3)

您可以使用数组:

$array = $textforDays = array(
    1 => 'Text for day 1',
    2 => 'Text for day 2',
    3 => 'Text for day 3',
    4 => 'Text for day 4',
    5 => 'Text for day 5',
    6 => 'Text for day 6',
);
echo $textforDays[$day];