CakePHP不修改控制器 实现招聘表格按closeDate字段升序排序
解决方案
你不需要修改控制器代码,直接在视图层对查询出来的$recruitments数组按closeDate字段升序排列即可,同时你现有代码里存在一个会破坏数据的小bug,我们也会一并修复:
实现步骤
- 第一步:在foreach遍历招聘数据之前,先对数组按截止日期升序排序,截止日期最近的排在最前面
- 第二步:修复原有代码中将
$recruitment对象错误赋值为日期字符串的问题,避免后续遍历出现异常
修改后完整代码
<table class="table table-striped table-hover"> <thead class="blue"> <tr> <th width="30%"> Company </th> <th width="50%"> File </th> <th width="20%"> Closing Date </th> </tr> </thead> <tbody> <?php // 新增:按closeDate升序排序数组,截止日期最近的排在最前 usort($recruitments, function($a, $b) { return strtotime($a->closeDate) - strtotime($b->closeDate); }); ?> <?php foreach ($recruitments as $key=>$recruitment): ?> <tr class="gradeX <?= $key % 2 == 1 ? 'even' : 'odd' ?>" role="row"> <td> <?= !empty($recruitment->Companies['name']) ? $recruitment->Companies['name']:$recruitment->othercompany ?> </td> <td> <?php if($recruitment->pdf): ?> <a href="<?= $this->request->webroot.'uploads/recruitmentfile/'.h($recruitment->pdf); ?>" title="Open File" target="_blank"><i class="fa fa-file-pdf-o fa-lg font-red-mint"></i> <?php $file=explode('_',$recruitment->pdf); echo $file[1]?$file[1]:$recruitment->pdf; ?> </a> <?php endif; ?> </td> <!--<td><?= h($recruitment->closeDate) ?></td>--> <td> <?php // 修复原有bug:不要直接给$recruitment赋值,改用单独变量存储日期 echo date("d F Y", strtotime($recruitment->closeDate)); ?> </td> </tr> <?php endforeach; ?> </tbody> </table>
补充说明
如果你用的是CakePHP 3.x及以上版本,也可以用CakePHP内置的集合方法排序,写法更简洁:
$recruitments = collection($recruitments)->sortBy('closeDate', SORT_ASC, SORT_REGULAR)->toArray();
两种写法都可以实现需求,不需要修改任何控制器逻辑。
内容的提问来源于stack exchange,提问作者Hooman
相关产品推荐
相关产品推荐

