简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM