从数组中删除值。我怎样才能让它发挥作用

时间:2018-01-13 07:21:45

标签: php arrays wordpress

我尝试使用自定义帖子类型的类别名称创建自定义导航栏。 我的方法是从类别名称创建一个数组,并使用数组中的值动态创建导航栏。其中一个类别名称是"未分类"我想摆脱那个。

当我为“未分类”'执行array_search时,问题是似乎没有找到任何东西,因此没有什么是未设置的。有人可以对此有所了解吗? 数组和部分代码如下。

数组($ categories)如下所示:

[3] => WP_Term Object
    (
        [term_id] => 2
        [name] => Logo
        [slug] => logo
        [term_group] => 0
        [term_taxonomy_id] => 2
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 10
        [filter] => raw
        [cat_ID] => 2
        [category_count] => 10
        [category_description] => 
        [cat_name] => Logo
        [category_nicename] => logo
        [category_parent] => 0
    )

[4] => WP_Term Object
    (
        [term_id] => 1
        [name] => Uncategorized
        [slug] => uncategorized
        [term_group] => 0
        [term_taxonomy_id] => 1
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 7
        [filter] => raw
        [cat_ID] => 1
        [category_count] => 7
        [category_description] => 
        [cat_name] => Uncategorized
        [category_nicename] => uncategorized
        [category_parent] => 0
    )

到目前为止我的代码看起来像这样:

<?php if ( get_post_type( get_the_ID() ) == 'work' ) {
 $categories = get_categories( array() );?>

<!-- display the contents of the array before unset -->
<pre>
  <?php print_r($categories);?>
</pre>
<!-- End display -->

<?php $key = array_search('uncategorized', $categories);
  printf ($key);
  unset($categories [$key]);

  // display contents of the array after unset
  foreach ( $categories as $category ) {
  printf( $category->name );
  // end display
  }
}
?>

1 个答案:

答案 0 :(得分:1)

您可以在foreach中添加if:

if($category->name != 'Uncategorized') {
    printf($category->name);
}

那就是它。