How Do You Extract Property Columns from Object Arrays in PHP?

Linda Hamilton
Release: 2024-10-20 09:00:30
Original
701 people have browsed it

How Do You Extract Property Columns from Object Arrays in PHP?

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>
Copy after login

The array_column() function takes two parameters:

  1. The array of objects to extract from.
  2. The property name to extract.

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!