【问题标题】:Better way to convert array of objects in PHP to associative array to populate a HTML select将 PHP 中的对象数组转换为关联数组以填充 HTML 选择的更好方法
【发布时间】:2016-07-03 20:34:08
【问题描述】:

假设我有一个具有以下结构的对象数组:

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
    )
)

我想把它变成下面的结构来填充一个 HTML 选择:

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

我总是这样做的方式是遍历原始数组并像这样构建一个新数组:

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

是否有更好/更简洁的方法来做到这一点,以便数组键是属性category_id,值是属性category_title

【问题讨论】:

  • array_walk($categories, function (&$value) { $value = (array) $value; });`
  • 试试这个array_map(function ($yourArray) {return $array->category_title;}, $yourArray);
  • 对于你的新数组,你必须再次使用循环来迭代你为什么要这样做的项目;虽然您可以在发布的循环中填充 html;为什么要分两步完成?
  • array_column('category_title') 应该很简单。 (尽管在您的示例中,如果您不使用 PHP 7,您可能需要将对象转换为数组)
  • 我应该澄清一下,数组中的索引需要是 category_id 属性

标签: php php-5.3 php-5.5 php-5.4 php-5.6


【解决方案1】:

如果您使用的是 PHP 5.5+,您可以使用专为此设计的超棒的新 array_column() 函数:

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 >

对于 5.5 以下的 PHP,someone on PHP.net 用纯 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;
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多