doomm4711 2018-10-24 02:08
浏览 1106
已采纳

Laravel Collection,用filter方法替换where方法

I have a collection on which I use the where method in order to get only the element that match like this:

myCollection->where('akey', $value);

When I try to transform this with the filter method, it fails:

myCollection->filter(function($value, $key){
   if($key === 'akey' && $value === $aValue)
      return true;
});

I try to use filter because I want to select items in the collection if theirs values are equals to multiple value. (where or Where or Where or Where basically).

  • 写回答

2条回答 默认 最新

  • douyi0219 2018-10-24 02:12
    关注

    I assume that $aValue is defined outside of the filter function, you should pass it to the callback function like this:

    myCollection->filter(function($value, $key) use ($aValue) {
      if($key === 'akey' && $value === $aValue)
          return true;
    });
    

    -- EDIT --

    Based on your example using where I think this should work.

    myCollection->filter(function($item) use ($aValue) {
       return $item->aKey === $aValue;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部