PHP - Extracting a property from an array of objects
To extract a property from an array of objects in PHP, you can use the array_column
function. This function returns an array containing all the values of a specific column in the input array.
Here's an example of how you can use array_column
:
<?php
$objects = [(object) ['id' => 1, 'name' => 'Alice'], (object) ['id' => 2, 'name' => 'Bob'], (object) ['id' => 3, 'name' => 'Charlie']];
$names = array_column($objects, 'name');
print_r($names);
// $names is now ['Alice', 'Bob', 'Charlie']
You can also use a combination of array_map
and get_object_vars
to extract properties from an array of objects:
<?php
$objects = [(object) ['id' => 1, 'name' => 'Alice'], (object) ['id' => 2, 'name' => 'Bob'], (object) ['id' => 3, 'name' => 'Charlie']];
$names = array_map(function ($object) {
return get_object_vars($object)['name'];
}, $objects);
print_r($names);
// $names is now ['Alice', 'Bob', 'Charlie']
You can also use a foreach loop to extract the properties from the objects:
<?php
$objects = [(object) ['id' => 1, 'name' => 'Alice'], (object) ['id' => 2, 'name' => 'Bob'], (object) ['id' => 3, 'name' => 'Charlie']];
$names = [];
foreach ($objects as $object) {
$names[] = $object->name;
}
print_r($names);
// $names is now ['Alice', 'Bob', 'Charlie']