dongzhi6087 2017-11-23 18:54
浏览 33
已采纳

过滤收藏品Laravel

Is there a way to filter a collection returned by database query on Laravel?

Returned collection is this

 1 => Person {#310 ▼
      #table: "person"
      #attributes: array:15 [▼
        "name" => "Jon Doe"
        "timeavailable" => "1,2,3,4,5,6,7,8"
 2 => Person {#310 ▼
      #table: "person"
      #attributes: array:15 [▼
        "name" => "Jon Moe"
        "timeavailable" => "1,2,5,7,8"

Here, I want to filter the timeavailable attribute. I only want to show results for 1,2,3 . Is there a way to filter this collection so that I only get something like this

1 => Person {#310 ▼
      #table: "person"
      #attributes: array:15 [▼
        "name" => "Jon Doe"
        "timeavailable" => "1,2,3"
 2 => Person {#310 ▼
      #table: "person"
      #attributes: array:15 [▼
        "name" => "Jon Moe"
        "timeavailable" => "1,2"

So, the filtered collection will have only 1,2,3 inclusions.

  • 写回答

1条回答 默认 最新

  • dswwuo1223 2017-11-23 19:13
    关注

    I think this is not the best solution, but it can be a way to solve for this problem. Check if this helps...

    Try to use the map of Collection. In the inner function, you can explode, intersect and explode timeavailable.

    $limiter = [1,2,3];
    $filtered = $array->map(function($person, $k) use ($limiter) {
        $ex = explode(',', $person->timeavailable);
        $intersect = array_intersect($limiter, $ex);
        $person->timeavailable = implode(",",$intersect);
        return $person;
    });
    

    This will work fine for small results, but if you are planning to run this with lots of results, it will be slow.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案