- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract a property from an array of objects in PHP
Given the below code, the task is to extract the ID of the my_object variable −
Example
$my_object = Array ( [0] => stdClass Object ( [id] => 12 ), [1] => stdClass Object ( [id] => 33 ), [2] => stdClass Object ( [id] => 59 ) )
The array_map function can be used for older versions of PHP. Below is a demonstration of the same.
$object_id = array_map(create_function('$o', 'return $o->id;'), $objects);
For PHP version 5.5 or higher, the array_column function could be used. Below is a demonstration of the same −
$object_id = array_column($my_object, 'id');
Output
This will produce the following output −
[12, 33, 59]
Advertisements