Laravel Collection - 删除包含空数组的对象

las*_*gun 1 collections filter laravel

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

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]=>
Run Code Online (Sandbox Code Playgroud)

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

这样剩下的就是具有非空数组的对象

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

我已经使用填充集合

 $things = $foos->get($thing->ID, collect());
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

Fou*_*SSI 5

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

$things = $foos->get($thing->ID, collect())->toArray();

foreach($things as $thing) {
   if(empty($thing['items'])) {
       unset($thing);
   }
}

$things = array_values($things);
Run Code Online (Sandbox Code Playgroud)

或者

使用 filter()

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

$things = $foos->get($thing->ID, collect());

$filtered = $things->filter(function ($value, $key) {
    return !empty($value->items) ;
});

$result = $filtered->all();
Run Code Online (Sandbox Code Playgroud)