Michelle
Michelle

Reputation: 135

PHP way to filter a big array by key?

I get a big data collection from a API, the array what I get has more objects who contains: id, name, place, zip.

Now I need to create filter this array, the code is:

$all_objects = $api_result->body->objects;

Of course I can do it with a foreach(), but what is the best way also for performances to filter it like get object by id 973?

Upvotes: 0

Views: 4871

Answers (1)

yivi
yivi

Reputation: 47319

You can use array_filter.

Assuming $all_objects is an array of objects with public properties as id, name, etc...

Example code:

$lookup = 973
$filtered = array_filter($all_objects, function($object) use($lookup) {
  return ($object->id === $lookup);
});

And now $filtered only have one (presumably) object with a public property "id" having 973

Note: As both @timurib and @federkun indicate, this is not the FASTEST way to filter an array. Doing a plain foreach would be, all other things being equal, faster. But you'd be shaving milliseconds and it could be argued that use of array_* functions make the code clearer.

Upvotes: 2

Related Questions