I have a database of 'post titles' containing a lot of duplicates, sometimes with more than 4 posts with the same title.
I want to build an array that gets the ID + Title of every duplicate entry.
$titles = array();
$duplicates = array(); //should be multi-dimensional array containing ID and title of each duplicate entry
//while statement
if (!in_array($post_title, $titles)){
array_push( $titles, $post_title) );
} else {
array_push( $duplicates, $post_title) );
}
//end while
The problem with this is that my $duplicates
array only contains the 'second' entry, or the 'duplicate' - I want to store both in the same array. How can I do this using something like array_diff
or merge or similar?
I.e. If two posts contain the same title, I want both of these to end up in my $duplicates array, with the respective id and title together.
There's the array_unique function too, but I can't quite figure out how to use this in this scenario...
Assuming $titles[] = array( 'id' => integer, 'title' => string );
and also that id:title is a 1:1 mapping
$count = array();
foreach( $titles as $title ) {
if( !isset($count[$title['id']]) ) {
$count[$title['id']] = 1;
} else {
$count[$title['id']]++;
}
}
foreach( $titles as $title ) {
if( $count[$title['id']] > 1 ) {
$duplicates[] = $title;
}
}
if (!in_array($post_title, $titles)){
array_push( $titles, $post_title) );
}
array_push( $duplicates, $post_title) );
//end while
This way you store the original and the duplicates in the $duplicates array.
Alternatively you can use: $titles = array_unique( $original_array );