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.
<code class="php">$cats = Array( (object) ['id' => 15], (object) ['id' => 18], (object) ['id' => 23] ); $idCats = array_column($cats, 'id');</code>
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:
<code class="php">$idCats = []; array_walk($cats, function ($cat) { $idCats[] = $cat->id; });</code>
However, using array_column() is a more concise and efficient approach, especially in PHP 7.0 and later versions.
The above is the detailed content of How Do You Extract Property Columns from Object Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!