Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


collecting column values into an array using -'php'


collecting column values into an array  using -'php'

One of the patterns that I frequently run across when developing is trying to collect a column/attribute value from a collection of objects into an array. For example:

$ids = array();
foreach ($documents as $document) {
    $ids[] =  $document->name;
}


Am I the only one who runs into this? And does PHP have a way to solve this in fewer lines? I've looked but found nothing.

Since I use an MVC framework I have access to a BaseUtil class which contains common functions that don't really fit in any specific classes. One solution proposed by a co-worker is:

class BaseUtil
{
    public static function collect($collection, $property) {
        $values = array();
        foreach ($collection as $item) {
            $values[] = $item->{$property};
        }
        return $values;
    }
}


Then I can just do:

$ids = BaseUtil::collect($documents, 'name');


Not too shabby. Anyone else have any other ideas? And am I crazy or does this seem like a problem that PHP should have solved a long time ago?
    

asked Sep 7, 2015 by rajesh
0 votes
2 views



Related Hot Questions



Government Jobs Opening


...