Better way to convert array of objects in PHP to associative array to populate a HTML select

Viewed 1006

Say I have an array of objects with the following structure:

Array ( 
    [0] => stdClass Object ( 
        [category_id] => 5 
        [category_title] => Meetings 
        [category_slug] => meetings 
        [category_summary] => This is the meetings category 
        [category_user_id] => 1 
        [category_created] => 2016-03-17 12:41:42 
        [category_modified] => 2016-03-17 12:41:42 
        [category_status] => 1 
        [category_deleted] => NULL
    ),
    [1] => stdClass Object ( 
        [category_id] => 9 
        [category_title] => Seminars 
        [category_slug] => seminars
        [category_summary] => This is the seminars category 
        [category_user_id] => 1 
        [category_created] => 2016-03-17 12:41:42 
        [category_modified] => 2016-03-17 12:41:42 
        [category_status] => 1 
        [category_deleted] => NULL
    ),
    [2] => stdClass Object ( 
        [category_id] => 15 
        [category_title] => Sporting Events 
        [category_slug] => sporting-events
        [category_summary] => This is the sporting events category 
        [category_user_id] => 1 
        [category_created] => 2016-03-17 12:41:42 
        [category_modified] => 2016-03-17 12:41:42 
        [category_status] => 1 
        [category_deleted] => NULL
    )
)

And I want to turn it into the following structure to populate an HTML select with:

Array ( 
    [5] => Meetings,
    [9] => Seminars,
    [15] => Sporting Events
)

The way I always do it is loop through the original array and build a new one like so:

// $categories contains the original array of objects
$select_categories = array();
foreach($categories as $category) {
    $select_categories[$category->category_id] = $category->category_title;
}

Is there a nicer / more concise way of doing this so that the array key is the property category_id and the value is the propery category_title?

1 Answers
Related