Extracting Property Columns from Object Arrays
To extract a column of properties from an array of objects in a single line, we can utilize PHP's array_column() function, introduced in PHP 7.0.
$cats = Array(
(object) ['id' => 15],
(object) ['id' => 18],
(object) ['id' => 23]
);
$idCats = array_column($cats, 'id');
The array_column() function takes two parameters:
In this case, we pass the $cats array as the first parameter and 'id' as the second parameter to extract the IDs of the cats.
If you're using PHP versions prior to 7.0, you can implement this using array_walk() and create_function(), as follows:
$idCats = [];
array_walk($cats, function ($cat) {
$idCats[] = $cat->id;
});
However, using array_column() is a more concise and efficient approach, especially in PHP 7.0 and later versions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3