pmiranda
pmiranda

Reputation: 8420

Laravel 5.3, PHP, filter an object of arrays by string

I have this object $data :

{#792 ▼
  +"cities": array:346 [▼
    0 => {#454 ▼
      +"name": "XXX"
      +"id": "1"
    }
    1 => {#452 ▼
      +"name": "ABC"
      +"id": "2"
    }
    1 => {#452 ▼
      +"name": "ABC"
      +"id": "2"
    }
    2 => {#433 ▼
      +"name": "XYZ"
      +"id": "3"
    }
etc...

And a string (a text value in the DB) like 1,3.

I want to filter the object with the object that contains that id in the string.

I was thinking to create a collection from $data, then an array from the string:

$dataC = collect ($data);
$array = explode(',', $string)

Create an empty collection and iterate the $dataC, and foreach value from the $dataC that has any of the values from $array, push it to the new empty collection. But for that, I need 2 chained foreachs. Is there a way that I can filter better the object with the values from the first string? Then iterate the array, and for each

Upvotes: 0

Views: 1340

Answers (2)

nice_dev
nice_dev

Reputation: 17805

It would be better to take advantage of Laravel collection methods itself.

$dataC = collect($data);
$filtered = $dataC->whereIn('id',explode(',', $string));
$filtered->all();

Use whereInStrict() if you want to strictly compare them with types.

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

Firstly you should explode your DB string to get an array of IDs.

After that you can simply use the array_filter function to get the matched cities only:

$ids = explode(',', $idsString);

$cities = array_filter($data->cities, static function($city) use ($ids) {
    return in_array($city->id, $ids);
});

var_dump($cities);

Upvotes: 1

Related Questions