【问题标题】:Remove duplicated objects that has the same value for a certain key, (wordpress: do not retrieve posts with same title)删除对某个键具有相同值的重复对象,(wordpress:不检索具有相同标题的帖子)
【发布时间】:2011-07-26 12:22:37
【问题描述】:

我到处寻找,但我在任何地方都找不到答案,而且我是 php 的初学者,所以我希望会有这么好心的人来帮助我。 我正在使用 wordpress,我正在使用这一行

$post_IDs = get_posts('category_name=glicinie');

要检索一个类别中的所有帖子,但在这个类别中我有很多重复的帖子,这是我获得的数组的一部分 [with print_r($post_IDs)]

Array ( 
[0] => stdClass Object 
( [ID] => 761 [post_author] => 2 [post_date] => 2011-07-26 12:07:17 
[post_title] => Flower )
[1] => stdClass Object
( [ID] => 760 [post_author] => 2 [post_date] => 2011-07-26 12:04:46   
[post_title] => Rainbow )
[2] => stdClass Object 
( [ID] => 770 [post_author] => 2 [post_date] => 2011-07-26 12:03:18 
[post_title] => Coconut )
[3] => stdClass Object 
( [ID] => 743 [post_author] => 5 [post_date] => 2011-07-26 11:38:48 
[post_title] => Coconut )
)

在此之后,我使用下面的代码在表单中填充每个帖子的标题和年份(即帖子的自定义字段)的选择。

foreach ($post_IDs as $post_ID) { 
$anno = get_post_meta($post_ID->ID, 'year', true); 
$title = $post_ID->post_title;
echo '<option value="'.$title.'">' . '[' . $year . '] ' . $title . '</option>'; 
}

现在你已经看到了,我有两个标题为“椰子”的帖子。所以在表格中的列表中,我会让 Coconut 帖子显示两次。 我想要的显然是只显示一次重复的帖子(如“椰子”)。 我想我应该在 foreach 之前对数组进行一种检查,但我不知道如何..所以在 foreach 中我只循环遍历具有不同“post_title”值的 ID..但是如何?

请原谅我的英语。 在此先感谢:)

【问题讨论】:

    标签: arrays wordpress object foreach duplicates


    【解决方案1】:

    我认为应该这样做。

    $got = array();
    foreach($post_IDs as $i => $d)
    {
        if(!in_array($d[post_title]),$got)
        {
            $got[] = $d[post_title];
            $out[] = $d;
        }
    }
    print_r($out);
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多