0

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

3
  • 1
    Please provide more details. Where's the code containing the two "chained foreachs"? Why not filter such data on the database level? Commented Jul 29, 2019 at 14:06
  • I'm coding right now whtat I put in the question, but I want to know if there's a better way. I'm using an external API, can't modify data from db. Commented Jul 29, 2019 at 14:09
  • cities is an array already, so you should be able to simply use array_filter Commented Jul 29, 2019 at 14:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

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.