Home  >  Article  >  Backend Development  >  How Do You Extract Property Columns from Object Arrays in PHP?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 09:00:30703browse

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>

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>

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!

Statement:
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