PHP: returning an array of single attributes from an array of objects
I miss Ruby’s shorthand collect method to return an array of single attributes:
animals.collect(&:name)
…so I’ve created a (less elegant) equivalent for PHP.
class ArrayExtensions
{
/**
* From an array of objects, create a new array containing only
* a single attribute of each object
*
* Similar to array.collect(&:attribute) in Ruby
*/
public static function collect_by_attribute($attribute, $array_of_objects)
{
if (!is_array($array_of_objects))
{
return array();
}
$output = array();
foreach ($array_of_objects as $object)
{
if (is_object($object) && isset($object->$attribute))
{
$output[] = $object->$attribute;
}
}
return $output;
}
}
Use it like this:
$colours = ArrayExtensions::collect_by_attribute('colour', $animals);
…and you’ll get a simple array containing just the attribute you’ve specified:
array('brown', 'blue', 'green')
Update
If you happen to be using PHP ActiveRecord, they have a function called collect that will accomplish the same thing.
$colours = ActiveRecord\collect($animals, 'colour');