我正在编辑类别。php模板和我需要一个当前类别子对象的数组。
我可以获得当前类别子级的数组,但键太多,我使用以下方法:
//get category ID
$catego = get_category( get_query_var( \'cat\' ) );
$cat_id = $catego->cat_ID;
//list current category childs
$catlist = get_categories(
array(
\'child_of\' => $cat_id,
\'orderby\' => \'id\',
\'order\' => \'ASC\'
) );
这给了我以下信息:
Array
(
[0] => WP_Term Object
(
[term_id] => 11
[name] => test1
[slug] => test1
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 3
[filter] => raw
[cat_ID] => 11
[category_count] => 3
[category_description] =>
[cat_name] => test1
[category_nicename] => test1
[category_parent] => 10
)
[1] => WP_Term Object
(
[term_id] => 12
[name] => test2
[slug] => test2
[term_group] => 0
[term_taxonomy_id] => 12
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 1
[filter] => raw
[cat_ID] => 12
[category_count] => 1
[category_description] =>
[cat_name] => test2
[category_nicename] => test2
[category_parent] => 10
)
)
现在,我想从这个数组创建一个只有[cat\\u ID]键的数组。我试过以下方法,但一无所获(
http://php.net/manual/en/function.array-column.php ):
$category_id = array_column($catlist, \'[cat_ID]\');
print_r($category_id);
有什么想法吗?提前谢谢。
最合适的回答,由SO网友:Sumesh S 整理而成
Try this :
// This converts the WP_Term Object to array.
$catlist = json_decode(json_encode($catlist),true);
$category_id = array_column($catlist, \'cat_ID\');
print_r($category_id);
SO网友:Sebastian Kurzynowski
您可以随时使用array_map()
$category_id = array();
$category_id = array_map( function ($data){
return $data[\'cat_ID\'];
}, $catlist);
或wordpress功能:
$category_id = array();
$category_id = wp_list_pluck( $catlist, \'cat_ID\' );