0

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?

6
  • and what's $all_objects? Commented Dec 23, 2016 at 10:04
  • edit your question with $all_objects's sample data or link of that api which you are calling. Use array_filter or you can check using array_key_exists functions for faster result. Commented Dec 23, 2016 at 10:07
  • ever heard of array_filter. Commented Dec 23, 2016 at 10:07
  • If you need to do a lot of lookups, you might want to re-index your array using the id as the key. Commented Dec 23, 2016 at 10:09
  • @Federkun this are real estate items, that's reason why it is objects :) Commented Dec 23, 2016 at 10:10

1 Answer 1

2

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.

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

6 Comments

array_filter definetly is not more effective then foreach. Function call in the PHP requires some overhead and always slower then inline code execution. If the question about perfomance then array_filter is wrong solution.
This isn't wrong, but the OP asked for the the best way, O(1), while array_filter has a time complexity of O(N)
You are both right. Didn't pick up on the performance part. Considering the code I assumed a more basic level of competence, which might have been wrong. My bad. I'll update the answer.
Can the use keyword accept an array? Example use($my_array).I have searched for its doc ,so far none
@ovicko, yes, it can accept any variable. the array wont be expanded, but inherited by the closure as is. you can pass several variables as well.
|

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.