PHP Convert Object Array To 1 Dimensional Array

PHP Convert Object Array To 1 Dimensional Array

0 1072

Thought I would share a function I wrote to convert property from an a array of objects to a one dimensional array. I ran into this problem because I wanted to select a single field from a DB query into a one dimensional array. I could not figure out how to get that from the DB. All that was available was a object array or array of arrays.

Here is a function to take care of this issue

function objects_to_one_dim($array, $property) {
            $oneDimArray = array();
            foreach($array as $o) {
                $oneDimArray[] = $o -> $property;
            }

            return $oneDimArray;
}

and can be utilized like this

 $newArray = objects_to_one_dim($myObjArray, 'a_property_in_the_object');

SIMILAR ARTICLES

NO COMMENTS

Leave a Reply