php - 删除多维数组中的重复条目
问题描述
嗨,我有 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;
}
在循环的开始和结束时。但它不起作用我想跳过重复的值并打印下一个。
解决方案
有一个单独的数组来维护 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
}
推荐阅读
- git - 已签出的 git 存储库的快照友好备份/复制 - 无需 rsync'ing .git 目录
- java - 获取方法 url 在文件名(源)之前包含 %E2%81%A9,为什么?
- c# - 如何在 C# 中获取单个 API 调用状态成功响应
- jmeter - 循环等待,直到我得到正确的响应
- c# - Awaiting with null coalescing operator thrown exception
- python - 带有自定义 MIB 的 Python 中的 SNMP 代理
- firebase - How to share a post in twitter clone app using Firestore as a database?
- android - Unable to open debugger port (8600) Android Studio in MAC
- python - Combining rows from one excel to another in a specific location
- python - 在 DataFrame 上应用具有多个参数的滚动函数