首页 > 解决方案 > 如何通过 PHP 显示下个月和上个月

问题描述

我只是想为这个数组添加功能,以便在点击时显示下个月。它目前显示当月的所有天数。

我的代码:

  <?php
      $workdays = array();
      $type = CAL_GREGORIAN;
      $month = date('n'); // Month ID, 1 through to 12.
      $year = date('Y'); // Year in 4 digit 2009 format.
      $day_count = cal_days_in_month($type, $month, $year); // Get the amount of days
      $next_date = date('n', strtotime($month .' +1 month'));
      $prev_date = date('n', strtotime($month .' -1 month'));
      //loop through all days
      for ($i = 1; $i <= $day_count; $i++)
      {
        $date = $year.$month.$i; //format date
        $get_name = date('l', strtotime($date)); //get week day
        $day_name = substr($get_name, 0, 3); // Trim day name to 3 chars
        //if not a weekend add day to array
        if($day_name != 'Sun' && $day_name != 'Sat')
        {
          $workdays[] = $i;
         }
      }
      foreach ($workdays as $workday => $test) {
        echo $test;

     }
   ?>

输出:

3 4 5 6 7 10 11 12  13 14 17 18 19  20  21  24  25  26  27  28

我需要这样的东西:

  <a href="?date=<?=$prev_date;?>">Previous month</a>
    <a href="?date=<?=$next_date;?>">Next month</a>

标签: phphtmlarraysloopscalendar

解决方案


据我了解,您需要显示一些指向当月工作日的链接以及指向上个月和下个月的链接。

以下代码需要PHP5.4或更高版本。

以下函数将返回一个月中工作日的链接:

const DATE_FOMAT = 'Y-m-d';
const LINK_SEPARATOR = " | ";

// get the reference date from the Query string so that we can print the calendar for any month
$refDateStr = $_GET['dt'] ?? date(DATE_FOMAT); // this requires PHP 7.1 or above

// this function will return the links to all working days
// in the given month (based on the $refDateStr)
function getDateLinks($refDateStr) {
    try {

        // first we check if the given date is valid or not
        $refDateDt = date_create_from_format(DATE_FOMAT, $refDateStr);

        if (!$refDateDt || $refDateDt->format(DATE_FOMAT) !== $refDateStr) {
            // date is not valid. We cannot proceed with this date
            throw new Exception('Invalid date supplied. Dates should be in ' . DATE_FOMAT .'.');
        }

        // now lets find first and last days of the given month
        // for convenience, the start date is set to the last date of past month
        $startDate = new DateTime($refDateDt->modify('first day of this month')->format(DATE_FOMAT));
        $startDate->sub(new DateInterval("P1D"));

        $endDate = new DateTime($refDateDt->modify('last day of this month')->format(DATE_FOMAT));

        $dateLink = null;
        // lets create the date links
        while ($startDate < $endDate) {
            $startDate->add(new DateInterval("P1D"));
            // exclude weekends... :-)
            if (in_array($startDate->format('D'), ['Sat', 'Sun']))
                continue;
            $dateLink .= getDateLinksFormated($startDate);
        }
        return rtrim($dateLink, LINK_SEPARATOR);
    } catch (Exception $exception) {
        echo $exception->getMessage();
    }
}

让我们决定如何显示日期链接

// This function create the date links
function getDateLinksFormated(DateTime $dt):string 
{
    return sprintf(
        "<a href='?%s'>%s</a>%s",
        $dt->format(DATE_FOMAT),
        $dt->format('d'),
        LINK_SEPARATOR
    );
}

现在是时候展示你的日历了!!!

// Link to the past month
echo "<a href='?dt=" . date(DATE_FOMAT, strtotime('-1 month', strtotime($refDateStr))) . "'><< PREV MONTH </a>";

// Link to the next month
echo getDateLinks($refDateStr);

// Link to the next month
echo "<a href='?dt=" . date(DATE_FOMAT, strtotime('+1 month', strtotime($refDateStr))) . "'> NEXT MONTH >></a>";

在此处阅读有关 PHP DateTime 类的更多信息


推荐阅读