PHP表格按年份筛选失效求助:仅显示2022年完成数据
解决PHP表格仅显示2022年完成数据的问题
问题核心原因
你的代码有两个直接导致条件失效的问题:
- if语句末尾多余的分号:
if($p->attr_finish_date == "2022" );末尾的分号会让这个条件变成一个空执行的语句,后续所有echo代码不管条件是否满足都会运行,等于没加任何判断。 - 日期格式可能不匹配:如果
attr_finish_date存储的是完整日期(比如2022-06-20),直接和字符串"2022"比较肯定不相等,需要先提取年份再判断。
修正后的代码
场景1:attr_finish_date仅存储年份(如"2022")
<table border = "1" style="width:100%" id="example"> <thead> <th>No</th> <th>Target Date</th> <th>Finish Date</th> <th>information</th> </thead> <tbody> <?php $j=1; foreach($data as $p){ // 去掉分号,用大括号包裹需要条件执行的代码块 if($p->attr_finish_date == "2022"){ echo "<tr>"; echo "<td>".$j++."</td>"; echo "<td>".$p->attr_target_date."</td>"; echo "<td>".$p->attr_finish_date."</td>"; echo "<td>".$p->attr_info."</td>"; echo "</tr>"; } } ?> </tbody> </table>
场景2:attr_finish_date是完整日期(如"2022-11-05")
如果存储的是带年月日的完整日期,需要先提取年份再做判断:
<table border = "1" style="width:100%" id="example"> <thead> <th>No</th> <th>Target Date</th> <th>Finish Date</th> <th>information</th> </thead> <tbody> <?php $j=1; foreach($data as $p){ // 从日期字符串前4位提取年份 $finishYear = substr($p->attr_finish_date, 0, 4); // 也可以用date函数解析(适用于标准日期格式) // $finishYear = date("Y", strtotime($p->attr_finish_date)); if($finishYear == "2022"){ echo "<tr>"; echo "<td>".$j++."</td>"; echo "<td>".$p->attr_target_date."</td>"; echo "<td>".$p->attr_finish_date."</td>"; echo "<td>".$p->attr_info."</td>"; echo "</tr>"; } } ?> </tbody> </table>
额外建议
- 不管条件代码块有几行,都用大括号包裹,能避免很多类似的语法错误。
- 如果数据来自数据库,更高效的方式是在SQL查询时直接筛选年份(比如
WHERE YEAR(attr_finish_date) = 2022),减少PHP端的数据处理量。
内容的提问来源于stack exchange,提问作者Skylar19
相关产品推荐
相关产品推荐

