donglu953744 2017-09-13 07:49
浏览 265
已采纳

如何从foreach中获取唯一值

I am trying to get unique values in a drop down list. Code for drop down is:

@foreach($admin_bills as $admin_bill)
   <?php $month = date('M, Y', strtotime($admin_bill->created_at)); ?>
   <option value="{{ $admin_bill->id }}">{{ $month }}</option>
@endforeach

This gives me all the values based on created_at. For example, if there are multiple entries on same month, it gives me results like

Aug, 2017
Aug, 2017
Aug, 2017
Sep, 2017
Sep, 2017

But if there are multiple entries on same month, I want them to show once in the drop down. So the result will be like:

Aug, 2017
Sep, 2017

I cannot simply use function like array_unique() here and the $admin_bill->id should get the first id of unique $month. How can I do that? Please help. I am using Laravel 5.4

Thank you.

  • 写回答

4条回答 默认 最新

  • douzhui8531 2017-09-13 08:00
    关注

    It is recommended that you solve this in the controller. Not in the view. In the controller you can write something like the following:

    $admin_bills->pluck('created_at')->map->format('M, Y')->distinct();
    

    I didn't test this but I think it will get you in the right direction.

    I am assuming that the created_at property is automatically parsed to a carbon object. Because that is the way Laravel normally works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决