"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 to Extract a Column of Properties from an Array of Objects in PHP?

How to Extract a Column of Properties from an Array of Objects in PHP?

Published on 2024-11-06
Browse:410

How to Extract a Column of Properties from an Array of Objects in PHP?

PHP: Efficiently Extract a Column of Properties from an Array of Objects

Many programming scenarios involve working with arrays of objects, where each object may have multiple properties. Occasionally, it becomes necessary to extract a specific property from each object to form a separate array. In PHP, achieving this goal in a single line, without resorting to loops or external functions, can be tricky.

One potential approach is utilizing the array_walk() function along with create_function. However, a more straightforward and elegant solution is available in PHP 7.0 and later.

array_column() to the Rescue

The array_column() function was introduced in PHP 7.0 and allows you to extract a specific column of data from an array of arrays or arrays of objects. Simply pass in your array of objects as the first parameter and the name of the desired property as the second parameter:

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

In this example, the $idCats variable will now contain an array of the IDs of all the cats objects.

Note for PHP Versions Prior to 7.0

If you are using a PHP version earlier than 7.0, you can still use the array_map() function:

$idCats = array_map(function($cat) { return $cat->id; }, $cats);

While this method is slightly more verbose, it achieves the same result.

By leveraging array_column() or array_map(), you can efficiently extract a column of properties from an array of objects in PHP, enabling you to streamline your code and improve performance.

Release Statement This article is reprinted at: 1729386019 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