You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP开发4行4列布局年历 新手入门实现问题咨询

实现方案

  1. 先补全布局样式,你已经写好了基础的行列HTML结构,增加对应的CSS即可实现4列等分布局:
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.row {
  display: flex;
  width: 100%;
}
.column {
  flex: 0 0 25%;
  border: 1px solid #e5e7eb;
  min-height: 200px;
  padding: 12px;
}
.column h2 {
  font-size: 18px;
  text-align: center;
  margin-bottom: 12px;
}
  1. 用PHP动态生成月份和对应日期,不用手动编写每个月份的重复结构,示例代码如下:
<?php
// 可自定义要生成的年份
$targetYear = 2021;
$monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
?>
<!-- 第一行:LOGO位 + 3个年份显示位 -->
<div class="row">
  <div class="column">
    <h2>LOGO GOES HERE</h2>
  </div>
  <?php for ($i = 0; $i < 3; $i++): ?>
  <div class="column">
    <h2><?php echo $targetYear; ?></h2>
  </div>
  <?php endfor; ?>
</div>
<?php
// 将12个月份拆分为3组,每组4个,对应后面3行布局
$monthGroups = array_chunk($monthNames, 4);
foreach ($monthGroups as $group):
?>
<div class="row">
  <?php foreach ($group as $idx => $monthName):
    // 计算当前月第一天是周几、当月总天数
    $currentMonth = $idx + 1;
    $firstDayTimestamp = strtotime("{$targetYear}-{$currentMonth}-01");
    $firstDayWeek = date('w', $firstDayTimestamp);
    $totalDays = date('t', $firstDayTimestamp);
  ?>
  <div class="column">
    <h2><?php echo $monthName; ?></h2>
    <!-- 星期表头 -->
    <div style="display: grid; grid-template-columns: repeat(7, 1fr); text-align: center; font-size: 12px; margin-bottom: 8px;">
      <span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>
    </div>
    <!-- 日期网格 -->
    <div style="display: grid; grid-template-columns: repeat(7, 1fr; gap: 4px; text-align: center; font-size: 12px;">
      <?php
      // 当月第一天之前的空白位置
      for ($i = 0; $i < $firstDayWeek; $i++) {
        echo '<span></span>';
      }
      // 输出当月所有日期
      for ($d = 1; $d <= $totalDays; $d++) {
        echo "<span>{$d}</span>";
      }
      ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endforeach; ?>
  1. 后续如果需要调整样式,直接修改CSS参数即可,要切换生成的年份只要修改$targetYear变量的取值。

内容的提问来源于stack exchange,提问作者Bret Shroats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:48:03