Retrieving Object Property Columns from an Array
Within an application, it is often necessary to extract a specific property from a list of objects. This task can be accomplished efficiently in PHP, especially with newer language versions.
Extracting Properties with array_column()
PHP 7.0 and later introduces the array_column() function, designed for this exact purpose. To extract a column of property values, simply define the cats array as an argument, followed by the target property name:
$idCats = array_column($cats, 'id');
This line of code effortlessly generates a new array containing the IDs of each cat object.
Additional Consideration
It's essential to note that for array_column() to operate correctly, the object property being targeted must either be an array or converted to one. This ensures the proper functionality of the function.
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