PHP - Extracting a property from an array of objects
If you have PHP 5.5 or later, the best way is to use the built in function array_column()
:
$idCats = array_column($cats, 'id');
But the son has to be an array or converted to an array
How to get object property from each object in an array?
The fastest way is simply looping (foreach
, for
, while
). Using callback functions will incur unnecessary overhead.
I would look to see if there's a way to create the list via the code that is building the initial array of objects.
Extract a string from an object inside an array: PHP
For example:
$data[0]->firstname
Maybe:
$arr = get_object_vars($data[0]);
$arr['firstname'];
Example:
$obj = (object) array('x' => 'foo');
$arr = [$obj];
print($arr[0]->x);
You will get: foo
Extract all ids from array of objects
Create an array which is the call
value indexed by the id
and then filter it. As the id is the index, then extract the keys for the ids...
$ids = array_keys(array_filter(array_column($array, "call", "id")));
print_r($ids));
Array
(
[0] => 1
[1] => 7
)
Although I think a foreach()
is a much more straight forward method.
Lumen/Laravel - Method to extract specific property from objects in an array of objects?
You can use the pluck
method on a Laravel collection (official docs here).
You just have to pass the column name that you want to retrieve as first parameter:
$ids = $ad_groups->pluck('id');
dd($ids);
Related Topics
Forget Password Page, Creating a Generated Password to Email to the User
Fatal Error: Call to Undefined Method MySQLi_Result::Fetch_All()
Get Coupon Data from Woocommerce Orders
How to Bind SQL Variables in PHP
How to Return a Proper Success/Error Message for Jquery .Ajax() Using PHP
Use One Laravel Migrations Table Per Database
Google Calendar API V3 - Authenticate with Hardcoded Credentials
Remotely Destroy a Session in PHP (User Logs in Somewhere Else)
Add Http:// Prefix to Url When Missing
Filling Gaps in Dates Returned from Database - Pure SQL Solution Possible
Get Root Node of Xml Doc Using Simplexml
Trying to Access Array Offset on Value of Type Null
What Is the Advantage of Using Try {} Catch {} Versus If {} Else {}
Php/Symfony/Doctrine Memory Leak