PHP - Extracting a Property from an Array of Objects

PHP - Extracting a property from an array of objects

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array

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

The fastest way is simply looping (foreach, for, while). Using callback functions will incur unnecessary overhead.

I would look to see if there's a way to create the list via the code that is building the initial array of objects.

Extract a string from an object inside an array: PHP

For example:

$data[0]->firstname

Maybe:

$arr = get_object_vars($data[0]);
$arr['firstname'];

Example:

$obj = (object) array('x' => 'foo');
$arr = [$obj];

print($arr[0]->x);

You will get: foo

Extract all ids from array of objects

Create an array which is the call value indexed by the id and then filter it. As the id is the index, then extract the keys for the ids...

$ids = array_keys(array_filter(array_column($array, "call", "id")));

print_r($ids));

Array
(
[0] => 1
[1] => 7
)

Although I think a foreach() is a much more straight forward method.

Lumen/Laravel - Method to extract specific property from objects in an array of objects?

You can use the pluck method on a Laravel collection (official docs here).

You just have to pass the column name that you want to retrieve as first parameter:

$ids = $ad_groups->pluck('id');
dd($ids);


Related Topics



Leave a reply



Submit