Assuming I have an array of objects in PHP, something like:
Array (
[0] => stdClass Object (
[id] => 1
[name] => Title One
)
[1] => stdClass Object (
[id] => 2
[name] => Title Two
)
[2] => stdClass Object (
[id] => 7
[name] => Title Seven
)
)
What is the best way (i.e. fastest) to get an array of the IDs? i.e. array(1,2,7)
I can loop manually but I feel there must be a better method.
Just saw this in the similar questions but there's a little debate over whether the accepted answer is really the best way, plus it's from 2 years ago. I'm on PHP 5.3.
To search a particular object, we will use the Array prototype find method. This returns a value on a given criterion, otherwise, it returns 'undefined'. It takes two parameters, one required callback function and an optional object, which will be set as a value of this inside the callback function.
To filter an array of objects based on a property:Use the Array. find() method to iterate over the array. On each iteration, check if the object's property points to the specific value. The find() method will return the first object that satisfies the condition.
To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop.
I'm using RedBean and for some reason passing in "getID" didn't work for me, so here is how I done it:
$ids = array_map(function($val){return $val->id;}, $objects);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With