B
B
Beeshop872021-06-16 12:37:14
PHP
Beeshop87, 2021-06-16 12:37:14

How to filter a collection of Illuminate\Support\Collection objects by array?

Greetings! I have a problem that I've been working on for a few days now. A beginner in someone else's code understands ...
There is a collection object containing an array of objects of store branches. You need to get a collection of branch objects whose ID matches the ID from the array for comparison.

Collection:

object(Illuminate\Support\Collection)#2149 (1) {
  ["items":protected]=>
  array(6) {
    [0]=>
    object(\Sale\Model\Store\Row)#2147 (4) {
      ["data":protected]=>
      array(18) {
        ["ID"]=>
        string(2) "96"
        ["ACTIVE"]=>
        string(1) "Y"
        ["ISSUING_CENTER"]=>
        string(1) "Y"
    }
    [1]=>
    object(\Sale\Model\Store\Row)#2148 (4) {
      ["data":protected]=>
      array(18) {
        ["ID"]=>
        string(3) "100"
        ["ACTIVE"]=>
        string(1) "Y"
        ["ISSUING_CENTER"]=>
        string(1) "Y"
    }
    [2]=>
    object(\Sale\Model\Store\Row)#2146 (4) {
      ["data":protected]=>
      array(18) {
        ["ID"]=>
        string(3) "124"
        ["ACTIVE"]=>
        string(1) "Y"
        ["ISSUING_CENTER"]=>
        string(1) "Y"
    }


Array to compare $arPickupID:

array(2) {
    [0]=> "96"
    [1]=> "100"
  }


My code that returns a collection with only the first match of

$shops - the original collection
getStoreId() - the method of the store object returning the ID

$filtered = $shops->filter(function($value) use($arPickupID)  {

                foreach ( $arPickupID as $item ) {
                    if ( $item == $value->getStoreId() ) {
                        return $value;
                    }
                }
            });


here is the filter() method itself:

public function filter(callable $callback = null)
    {
        if ($callback) {
            return new static(Arr::where($this->items, $callback));
        }

        return new static(array_filter($this->items));
    }


Any ideas, comrades?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2021-06-16
@Beeshop87

https://laravel.com/docs/8.x/collections#method-wherein

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question