【问题标题】:Laravel Collection - Remove Object containing empty arrayLaravel 集合 - 删除包含空数组的对象
【发布时间】:2020-02-11 13:35:31
【问题描述】:

我有一个对象集合 - 其中一些包含空数组。

object(Illuminate\Support\Collection)#34225 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34226 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34227 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34228 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Database\Eloquent\Collection)#23760 (1) {
  ["items":protected]=>
  array(2) {
    [0]=>
    object(App\Models\File)#23766 (27) {
      ["primaryKey":protected]=>
      string(6) "FileID"
      ["table":protected]=>

我可以使用某人的帮助来过滤对象集合,以便包含空数组的对象消失/删除。

所以剩下的就是非空数组的对象

object(Illuminate\Database\Eloquent\Collection)#23760 (1) {
  ["items":protected]=>
  array(2) {
    [0]=>
    object(App\Models\File)#23766 (27) {
      ["primaryKey":protected]=>
      string(6) "FileID"

我已经使用

填充了集合
 $things = $foos->get($thing->ID, collect());

任何帮助将不胜感激

【问题讨论】:

    标签: laravel filter collections


    【解决方案1】:

    您可以使用toArray() 方法将其转换为数组

    $things = $foos->get($thing->ID, collect())->toArray();
    
    foreach($things as $thing) {
       if(empty($thing['items'])) {
           unset($thing);
       }
    }
    
    $things = array_values($things);
    

    或者

    使用 filter()

    filter 方法使用给定的回调过滤集合,只保留那些通过给定真值测试的项目:

    $things = $foos->get($thing->ID, collect());
    
    $filtered = $things->filter(function ($value, $key) {
        return !empty($value->items) ;
    });
    
    $result = $filtered->all();
    

    【讨论】:

    • 现在我有一个数组,但仍然包含空数组
    • array(0) { }array(2) { [0]=> object(App\Models\File)#23766 (27) { ["primaryKey":protected]=> string(6) "FileID" ["table":protected]=>
    • 我希望删除所有 array(0) 项。
    • 很高兴为您提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。请参阅:How does accepting an answer work? 了解更多信息
    【解决方案2】:

    Collection Unexpected:) 有方法过滤器。

    $collection = collect([
    [],
    ['1'],
    [],
    ]);
    
    $collection->filter(); // will return collection with only [ [1] ]
    

    【讨论】:

    • 仍然包含带有 array(0) { } 的项目
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2019-07-23
    • 2021-06-26
    • 2018-11-21
    相关资源
    最近更新 更多