Say I have an array of Person objects and the person objects have properties firstName, lastName, and age. Now suppose I want an array of the firstnames of all these person objects. How can I convert this array of Person objects into an array of firstname strings?
Is there some combination of array functions I can use to do it or do I just have use a for loop and create a new array?
You can use array_map
class Person
{
public $firstName ;
public $lastName ;
public $age ;
function __construct($firstName,$lastName,$age)
{
$this->firstName = $firstName ;
$this->lastName = $lastName ;
$this->age = $age ;
}
}
$list = array();
$list[] = new Person("John", "Smith", 22);
$list[] = new Person("Jon", "Doe", 19);
$list[] = new Person("Jane", "Stack", 21);
$lastNames = array_map(function($var){return $var->lastName ; } ,$list);
var_dump($lastNames);
Output
array
0 => string 'Smith' (length=5)
1 => string 'Doe' (length=3)
2 => string 'Stack' (length=5)
You can loop through the array of person objects, and then loop through the person object and create array from the firstname property. See an example, which coincidently uses a person class as an example:
A simple loop would be the best:
$persons = getPersons();
$firstnames = array();
foreach($persons as $person) {
$firstnames[] = $person->getFirstName();
}
You have to loop through the array of objects. Either use the normal foreach
or use array_map
.
function get_first_name($person)
{
return $person->firstName;
}
$firstNames = array_map('get_first_name', $people);