簡體   English   中英

從多維數組創建新數組

[英]Create new array from multidimensional 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
            )

)

我想變成以下數組:

[
    { 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;
}

但它只返回數組中的最后一項。 如何遍歷每個數組行並創建所需的數組?

你不是在創建新的數組元素,你只是覆蓋了同一個數組中的值。

此外,您從$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