How to unset (remove) a collection element after fetching it?

后端 未结 5 1406
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 18:28

I have a collection which I want to iterate and modify while I fetch some of its elements. But I could\'t find a way or method to remove that fetched element.



        
相关标签:
5条回答
  • 2020-12-08 18:43

    Or you can use reject method

    $newColection = $collection->reject(function($element) {
        return $item->selected != true;
    });
    

    or pull method

    $selected = []; 
    foreach ($collection as $key => $item) {
          if ($item->selected == true) {
              $selected[] = $collection->pull($key);
          }
    }
    
    0 讨论(0)
  • 2020-12-08 18:46

    Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

    If you have the key already you can just use PHP unset.

    I prefer this, because it clearly modifies the collection in place, and is easy to remember.

    foreach ($collection as $key => $value) {
        unset($collection[$key]);
    }
    
    0 讨论(0)
  • 2020-12-08 18:46

    If you know the key which you unset then put directly by comma separated

    unset($attr['placeholder'], $attr['autocomplete']);
    
    0 讨论(0)
  • 2020-12-08 18:51

    I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.

    See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578

    So, when using foreach if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.

    /**
     * Filter all `selected` items
     *
     * @link https://laravel.com/docs/7.x/collections#method-filter
     */
    $selected = $collection->filter(function($value, $key) {
        return $value->selected;
    })->toArray();
    
    0 讨论(0)
  • 2020-12-08 18:56

    You would want to use ->forget()

    $collection->forget($key);
    

    Link to the forget method documentation

    0 讨论(0)
提交回复
热议问题