【问题标题】:Search Value in Laravel Collection在 Laravel 集合中搜索值
【发布时间】:2019-05-15 05:20:40
【问题描述】:

我有一个包含用户联系人的集合,我想在这个集合中搜索一个值。

我试过 $itemCollection->where('username', $search);但它仅在 $search 值完全等于用户名时向我显示,但我想获得也包含该值的结果。

例如,我将“yunus”值作为用户名,当我搜索“yunus”时它运行良好,但如果我也搜索“yun”或“y”值,我想查看结果。

我搜索了它,我确实发现我必须使用 where 'like' 方法,但我确实发现它不适用于集合:(

我的获取用户联系人的功能,其中包含我搜索的用户名值

public function index(Request $request)
    {

      $contacts = [];
      $user = request()->user();
      $search = $request->search;

      Contact::for($user->id)
      ->orderBy('created_at', 'DESC')
      ->get()
      ->each(function ($contact) use ($user, &$contacts) {
          $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
          $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
      });

      $itemCollection = collect($contacts);

      $filtered = $itemCollection->where('username', $search);


      $filtered->all();


        return response()->json($filtered);
    }

结果:Json output

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    尝试使用filter() 而不是where()

    $itemCollection = collect($contacts);
    $filtered = $itemCollection->filter(function($item) use ($search) {
        return stripos($item['username'],$search) !== false;
    });
    

    https://laravel.com/docs/5.7/collections#method-filter

    【讨论】:

    • 我收到了这个错误; “strpos() 期望参数 1 是字符串,给定数组”
    • 抱歉,我不确定您的联系人数组结构是什么,但$item 是集合中的一个元素......也许$item['username'] 包含您正在搜索的用户名?我已经更新了答案。
    • 谢谢,它现在可以工作了:) 但是有区分大小写的,我怎样才能关闭区分大小写?
    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2019-03-10
    • 2016-02-12
    相关资源
    最近更新 更多