1

I have an Collection of objects - some of which contain empty arrays.

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]=>

I could use someones help in filtering the Collection of objects so that the objects containing empty arrays are gone/removed.

So that all that remains are the objects with non empty arrays

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

I have populated the collection using

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

Any help would be greatly appreciated

2 Answers 2

5

You may convert it to an array using toArray() method

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

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

$things = array_values($things);

Or

Using filter()

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

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

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

$result = $filtered->all();
Sign up to request clarification or add additional context in comments.

4 Comments

Now I have an array but contains empty arrays still
array(0) { }array(2) { [0]=> object(App\Models\File)#23766 (27) { ["primaryKey":protected]=> string(6) "FileID" ["table":protected]=>
I wish to remove all array(0) items.
Glad to help, if this answer solved your problem please mark it as accepted by clicking the check mark next to the answer. see: How does accepting an answer work? for more information
1

Collection Unexpectedly :) has a method filter.

$collection = collect([
[],
['1'],
[],
]);

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

This is only if you have a collection of arrays. If you have a collection of collections you would need to pass the filter function. fn(Collection $c) => $c->isNotEmpty()

1 Comment

Still contains the items with array(0) { }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.