如何从数组中排除项目?

时间:2011-11-20 15:40:06

标签: php arrays

在下面的PHP函数中,我想要排除cat_ID=1

我该怎么做?

function get_cats(){
    $post_cats= array();
    $categories = get_the_category();
    foreach($categories as $cat){
        array_push($post_cats, $cat->cat_ID);
    }
    return $post_cats;
}

get_the_category()返回当前帖子分配到的所有类别的数组

3 个答案:

答案 0 :(得分:3)

foreach($categories as $cat){  
    if ($cat->cat_ID == 1)
       continue;
    array_push($post_cats, $cat->cat_ID);
}

答案 1 :(得分:2)

foreach ($categories as $cat) {
    if ($cat->cat_ID != 1) {
        $post_cats[] = $cat->cat_ID;
    }
}

这将在数组构建时排除该值。否则,您可以使用数组搜索操作来获取稍后对应于该特定ID值的键,然后取消设置()该特定键。

答案 2 :(得分:1)

非常非常微不足道的问题。使用

if ($cat->cat_ID != 1)

array_push

之前
相关问题