Remove duplicated objects that has the same value for a certain key, (wordpress: do not retrieve posts with same title)
i looked for everywhere but i can't find an answer anywhere, and i'm a beginner with php so i hope that there will be someone so kind to help me. i'm working with wordpress and i'm using this line
$post_IDs = get_posts('category_name=glicinie');
to retrieve all posts in a category, but in this category i have lot of duplicates posts, here's a portion of the array that i obtain [ 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] => 20开发者_JAVA技巧11-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 )
)
after this i use this code below to populate a select in a form with title and year (that is a custom field of the post) for each post.
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>';
}
now you've seen before that i have two posts titled as "Coconut"..so in the list in the form i'll have the post Coconut displayed twice. what i want is obvously to display the duplicated posts (like "Coconut") only once.. i think i should make a kind of check of the array before the foreach but i don't know how..so that in the foreach i loop only through the ID's that have a different "post_title" value..but how?
forgive my english. thank in advance :)
I think this should do it.
$got = array();
foreach($post_IDs as $i => $d)
{
if(!in_array($d[post_title]),$got)
{
$got[] = $d[post_title];
$out[] = $d;
}
}
print_r($out);
精彩评论