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:
// $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_types_array = [];
foreach ($post_types as $post_type) {
$post_types_array[] = [
'value' => $post_type->name,
'label' => $post_type->labels->name
];
}