geoffs3310 geoffs3310 - 5 months ago 17
PHP Question

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

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
?

Answer

If you're using PHP 5.5+, you can use the awesome new array_column() function, designed specifically for this:

php > $array = [
php >     0 => [
php >         'category_id' => 5,
php >         'category_title' => 'Meetings',
php >         'category_slug' => 'meetings',
php >         'category_summary' => 'This is the meetings category',
php >     ],
php >     1 => [
php >         'category_id' => 9,
php >         'category_title' => 'Seminars',
php >         'category_slug' => 'seminars',
php >         'category_summary' => 'This is the seminars category',
php >     ],
php >     2 => [
php >         'category_id' => 15,
php >         'category_title' => 'Sporting Events',
php >         'category_slug' => 'sporting-events',
php >         'category_summary' => 'This is the sporting events category',
php >     ],
php > ];
php >

php > var_dump(array_column($array, 'category_title', 'category_id'));
array(3) {
  [5]=>
  string(8) "Meetings"
  [9]=>
  string(8) "Seminars"
  [15]=>
  string(15) "Sporting Events"
}
php >

For PHP below 5.5, someone on PHP.net implemented it in pure PHP:

/**
 * Provides functionality for array_column() to projects using PHP earlier than
 * version 5.5.
 * @copyright (c) 2015 WinterSilence (http://github.com/WinterSilence)
 * @license MIT
 */
if (!function_exists('array_column')) {
    /**
     * Returns an array of values representing a single column from the input
     * array.
     * @param array $array A multi-dimensional array from which to pull a
     *     column of values.
     * @param mixed $columnKey The column of values to return. This value may
     *     be the integer key of the column you wish to retrieve, or it may be
     *     the string key name for an associative array. It may also be NULL to
     *     return complete arrays (useful together with index_key to reindex
     *     the array).
     * @param mixed $indexKey The column to use as the index/keys for the
     *     returned array. This value may be the integer key of the column, or
     *     it may be the string key name.
     * @return array
     */
    function array_column(array $array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (!is_array($subArray)) {
                continue;
            } elseif (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $result[$subArray[$indexKey]] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $result[$subArray[$indexKey]] = $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}