How to get object property from each object in an array?
Assuming I have an array of objects in PHP, something like:
Array (
[0] => stdClass Object (
[id] => 1
[name] => Title One
)
[1] => stdClass Object (
[id] => 2
[name] => Title Two
)
[2] => stdClass Object (
[id] => 7
[name] => Title Seven
)
)
What is the best way (i.e. fastest) to get an array of the IDs? i.e. array(1,2,7)
I can loop manually but I feel there must be a better method.
Just saw this in the similar questions but there's a little debate over whether the accepted answer is rea开发者_如何学运维lly the best way, plus it's from 2 years ago. I'm on PHP 5.3.
You can use array_map
to get the IDs from each element.
function getID($a){
return $a->id;
}
$IDs = array_map('getID', $array);
Demo: http://ideone.com/nf3ug
Since PHP 7.0 you may use the builtin function array_column
for that, which takes an input array and the name of the property you want to pluck:
$ids = array_column($input, 'id');
// array(0 => 1, 1 => 2, 2 => 7)
As a third parameter, you may optionally supply an index-key as well:
$ids = array_column($input, 'name', 'id');
// array(1 => 'Title One', 2 => 'Title Two', 7 => 'Title Seven')
Please note that, although it's already available in PHP 5.5.0, support for an array of objects was first introduced in PHP 7.0.
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.
I'm using RedBean and for some reason passing in "getID" didn't work for me, so here is how I done it:
$ids = array_map(function($val){return $val->id;}, $objects);
You can do it easily with ouzo goodies
$result = array_map(Functions::extract()->id, $objects);
or with Arrays (from ouzo goodies)
$result = Arrays::map($objects, Functions::extract()->id);
Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).
Did you try the array_keys function?
EDIT:
<?php
$ids = array();
for($c=0; $c<count($the_array); $c++) $ids[$c] = $the_array[$c]->id;
?>
You can also use extract_property() which is a well tested library designed specifically for this job (disclaimer: I am the author).
精彩评论