"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do You Extract Property Columns from Object Arrays in PHP?

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

Published on 2024-11-14
Browse:291

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.

$cats = Array(
    (object) ['id' => 15],
    (object) ['id' => 18],
    (object) ['id' => 23]
);

$idCats = array_column($cats, 'id');

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:

$idCats = [];
array_walk($cats, function ($cat) {
    $idCats[] = $cat->id;
});

However, using array_column() is a more concise and efficient approach, especially in PHP 7.0 and later versions.

Release Statement This article is reprinted at: 1729385956 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3