简体   繁体   English

从多维数组创建新数组

[英]Create new array from multidimensional array

I have the following array:我有以下数组:

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
            )

)

I would like to turn in into the following array:我想变成以下数组:

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

I'm using a foreach loop to create a new array:我正在使用 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;
}

But it returns only the last item from the array.但它只返回数组中的最后一项。 How is it possible to go trough each array row and create the desired array?如何遍历每个数组行并创建所需的数组?

You're not creating new array elements, you're just overwriting the values in the same array.你不是在创建新的数组元素,你只是覆盖了同一个数组中的值。

Also, you're getting the wrong elements from the $post_type object.此外,您从$post_type对象中获取了错误的元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM