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.
The above is the detailed content of How to Retrieve Object Property Columns from an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!