Retrieving Object Property Arrays in PHP
When dealing with arrays of objects, it can be necessary to extract specific columns of properties for further processing. This article explores a concise method for extracting these columns in a single line using the array_column() function.
Array of Objects
Consider the following array of cat objects:
<code class="php">$cats = [ (object)['id' => 15], (object)['id' => 18], (object)['id' => 23] ];</code>
array_column() Function
To extract the column of IDs from these objects, we can leverage the array_column() function. Introduced in PHP 7.0, this function provides a convenient way to retrieve columns of properties from arrays of objects or arrays.
Usage
To use array_column(), we specify the input array as the first parameter and the desired property name as the second parameter. For instance, to extract the IDs from our $cats array, we would use:
<code class="php">$idCats = array_column($cats, 'id');</code>
The result would be an array containing the IDs of the cats:
<code class="php">[15, 18, 23]</code>
Note for PHP Versions Prior to 7.0
If you are using PHP versions prior to 7.0, array_column() is not available. Alternative approaches such as array_walk() or a custom function can be used for property extraction.
The above is the detailed content of How Does PHP\'s array_column() Function Extract Columns of Object Properties?. For more information, please follow other related articles on the PHP Chinese website!