【问题标题】:Create new array from multidimensional array从多维数组创建新数组
【发布时间】:2021-11-13 09:49:01
【问题描述】:

我有以下数组:

Array
(
    [movies] => WP_Post_Type Object
        (
            [name] => movies
            [label] => Movies
            [labels] => stdClass Object
                (
                    [name] => Popular Movies
                    [singular_name] => Movie
                    [add_new] => Add New
                    [add_new_item] => Add New Movie
                )

            [description] => Movie news and reviews
        )

    [portfolio] => WP_Post_Type Object
        (
            [name] => portfolio
            [label] => Portfolio
            [labels] => stdClass Object
                (
                    [name] => New Portfolio Items
                    [singular_name] => Portfolio
                    [add_new] => Add New
                    [add_new_item] => Add New Portfolio
                )

            [description] => Portfolio news and reviews
        )


       [fruits] => WP_Post_Type Object
            (
                [name] => fruits
                [label] => My Fruits
                [labels] => stdClass Object
                    (
                        [name] => My Fruits
                        [singular_name] => Fruit
                        [add_new] => Add New
                        [add_new_item] => Add New Fruit
                    )

                [description] => Fruits news and reviews
            )

)

我想变成如下数组:

[
    { value: 'movies', label: 'Popular Movies' },
    { value: 'portfolio', label: 'New Portfolio Items' },
    { value: 'fruit', label: 'My Fruits' },
]

我正在使用 foreach 循环来创建一个新数组:

// $post_types is the array 

foreach ( $post_types as $post_type ) { 
    $post_types_array['value'] = $post_type->label;
    $post_types_array['label'] = $post_type->name;
}

但它只返回数组中的最后一项。如何遍历每个数组行并创建所需的数组?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    你没有创建新的数组元素,你只是覆盖了同一个数组中的值。

    另外,您从 $post_type 对象中获取了错误的元素。

    $post_types_array = [];
    foreach ($post_types as $post_type) {
        $post_types_array[] = [
            'value' => $post_type->name, 
            'label' => $post_type->labels->name
        ];
    }
    

    【讨论】:

    • 为了使代码更易于阅读,您可能希望将数组的属性放在单独的行中...
    猜你喜欢
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2019-07-25
    • 2014-09-25
    相关资源
    最近更新 更多