簡體   English   中英

從數組中刪除值。 我該如何運作

[英]Removing a value from an array. How can I get it to work

我正在嘗試通過使用自定義帖子類型的類別名稱來創建自定義導航欄。 我的方法是根據類別名稱創建一個數組,並使用該數組中的值動態創建導航欄。 類別名稱之一是“未分類的”,我想擺脫該名稱。

問題是,當我對“未分類”執行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
  }
}
?>

您可以在foreach中添加if:

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

而已。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM