Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object property from each object in an array?

Tags:

php

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.

like image 208
DisgruntledGoat Avatar asked Jun 24 '11 00:06

DisgruntledGoat


People also ask

How do you find a specific object in an array of objects?

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.

How do you filter only one property from an array of objects?

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.

How do you find the value of an array of objects?

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.


1 Answers

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);
like image 52
malhal Avatar answered Oct 23 '22 12:10

malhal