嗨,我有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
)
)
现在我正在获取柴油的重复条目,因此它被打印了两次,我不想删除我尝试过的重复条目array_unique,但是由于它是数组中的对象,所以它不起作用,我也尝试过
$term_id = get_the_ID();
if($term_id == get_the_ID()){
continue;
}
在循环的开始和结束。但是它不起作用,我想跳过重复的值并打印下一个。
答案 0 :(得分: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
}