【问题标题】:Remove Duplicates Entries Inside an Multidimensional Array删除多维数组中的重复条目
【发布时间】:2019-12-14 19:59:31
【问题描述】:

嗨,我有 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);

而terms变量的输出是这样的

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;
}

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

【问题讨论】:

  • “和其他术语变量的输出是这样的” - 这不是那个变量的“输出”,它们是 多个 不同的输出,来自您为不同职位获得的条款。您没有在 $terms 中有重复项,当将其附加到 $post_data 变量时,您正在创建 个重复项。只需将您正在处理的每个术语 id 放入一个数组中,然后使用 in_array 检查当前术语 id 是否已经存在,然后再为其添加新选项。

标签: php loops duplicates unique


【解决方案1】:

有一个单独的数组来维护 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    相关资源
    最近更新 更多