首页 > 解决方案 > 删除多维数组中的重复条目

问题描述

嗨,我有 php 数组,我在 While 循环中运行 foreach

    if ( $the_query->have_posts() ) { 

    while ($the_query->have_posts()) { 
        $the_query->the_post();
        $get_the_ids[]= get_the_ID();


        $terms = wp_get_post_terms( get_the_ID(), 'wpcm_alimentazione',array("fields" => "all") );


        foreach ($terms as $key_term => $value_term) {
            $post_data.= "<option value='{$value_term->term_id}'>{$value_term->name}</option>";
        }


        //

    }


}

print_r($post_data);

而其他术语变量的输出是这样的

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 15
            [name] => Gasolina
            [slug] => gasolina
            [term_group] => 0
            [term_taxonomy_id] => 15
            [taxonomy] => wpcm_alimentazione
            [description] => 
            [parent] => 0
            [count] => 2
            [filter] => raw
        )

)
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 17
            [name] => Diesel
            [slug] => diesel
            [term_group] => 0
            [term_taxonomy_id] => 17
            [taxonomy] => wpcm_alimentazione
            [description] => 
            [parent] => 0
            [count] => 2
            [filter] => raw
        )
[1] => WP_Term Object
        (
            [term_id] => 25
            [name] => LPG
            [slug] => LPG
            [term_group] => 0
            [term_taxonomy_id] => 25
            [taxonomy] => wpcm_alimentazione
            [description] => 
            [parent] => 0
            [count] => 2
            [filter] => raw
        )

)
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 17
            [name] => Diesel
            [slug] => diesel
            [term_group] => 0
            [term_taxonomy_id] => 17
            [taxonomy] => wpcm_alimentazione
            [description] => 
            [parent] => 0
            [count] => 2
            [filter] => raw
        )

)

现在我得到了 Diesel 的重复条目,所以它被打印了两次

$term_id =  get_the_ID();
if($term_id ==  get_the_ID()){
continue;
}

在循环的开始和结束时。但它不起作用我想跳过重复的值并打印下一个。

标签: phploopsduplicatesunique

解决方案


有一个单独的数组来维护 terms_ids 以检查重复项

$terms_array = array();

在循环并打印时,

只需检查它是否存在于 $terms_array

while ($the_query->have_posts()) {
if(in_array($term_id, $terms_array))
{
   continue; 
}
just add that term_id to an array after checking
$terms_array[$term_id] = $term_id;

// All your normal code here
}

推荐阅读