[英]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.