【发布时间】:2021-12-30 19:23:14
【问题描述】:
我有这个数组 $post_types 和对象:
Array
(
[vegetables] => WP_Post_Type Object
(
[name] => sports
[label] => Sports
[taxonomies] => Array
(
[0] => country
[1] => type
)
[has_archive] => 1
[show_in_rest] => 1
)
[fruits] => WP_Post_Type Object
(
[name] => fruits
[label] => Fruits
[taxonomies] => Array
(
[0] => color
[1] => taste
[2] => origin
)
[has_archive] => 1
[show_in_rest] => 1
)
)
我想将数组 $prepend 中的对象添加到其中:
Array
(
[post] => WP_Post_Type Object
(
[name] => post
[label] => Post
[taxonomies] => Array
(
[0] => categories
[1] => tags
)
[has_archive] => 1
[show_in_rest] => 1
)
)
我尝试了以下方法:
$post_types[] = $prepend
这会将它添加到 $post_types 数组的末尾,并像这样包装一个索引为 0 的数组:
[0] => Array
(
[post] => WP_Post_Type Object
...
)
...
我也试过array_unshift($post_types , $prepend);
它将它添加到开头,但又将它包装在array 中。如何添加
[post] => WP_Post_Type Object
(
[name] => post
[label] => Post
...
到$post_types 没有[0] => array( ... 包裹在[post] => WP_Post_Type Object ... 周围?
我也尝试了array_unshift($post_types, array_column($prepend, 'post')),但添加了一个空数组。
【问题讨论】:
-
array_unshift无法维护密钥“post”。您必须编写一段自定义代码,例如。从头开始构建您的目标数组,并以所需的格式和顺序(以及您想要的键)添加元素。 -
$post_types['post'] = $prepend['post'];给新出现的键名指定你想要的键名,否则它必须添加一个数字键 -
array_merge()不起作用? -
array_merge(['post'=>$prepend['post']], $post_types)