Reputation: 352
How can I check whether the next row is a duplicate one. if duplicate it will move to the next row.
Example:
1st row: 1900
2nd row: 1900
3rd row: 2000
How can mysql and php can do these results:
1st row: 1900
2nd row: 2000
3rd row: 1900
Is this possible or any possible codes?
<?php
$array = array(1900,1900,2000);
$checkDuplicates = array_diff($array);
print_r($checkDuplicates);
?>
The next thing how can i move the duplicate row?
Upvotes: 2
Views: 374
Reputation: 1371
You can store last row in temporary variable $last and in foreach loop do this:
$last = '';
foreach ($array as $row){
if ($row== $last){
continue;
} else {
$returnArray[] = $row;
}
$last = $row;
}
var_dump($returnArray);
Upvotes: 2
Reputation: 81
This problem is elementary programming, you would normally have a problem like this in the first week of uni.
array_diff won't help you, it compares two different arrays, whereas you're looking for comparison of the previous element within an array.
The same principle applies whether it is coming from mysql or an array.
Also, ask yourself the question, does this data need to be sorted first ?
Try this
<?php
$my_array = array(1900,1900,2000);
$tmp = null ;
for( $i = 0 ; $i<count($my_array) ; $i++) {
if( $my_array[$i] != $tmp ){
echo "\nValue $i is different to the last one,
should I do extra stuff here ?";
} else {
echo "\nValue $i is the same as the last one and equals $tmp";
}
$tmp = $my_array[$i] ;
}
?>
The output of the above code is..
Value 0 is different to the last one, should I do extra stuff here ?
Value 1 is the same as the last one and equals 1900
Value 2 is different to the last one, should I do extra stuff here ?
Determining whether the action is occurring on the first entry is a simple matter of checking the value of $i
Upvotes: 0
Reputation: 32350
You need to stack a second array with unique values.
<?php
$array = array(1900,1900,2000);
$array2 = array();
foreach ($array as $val) {
if (!in_array($val, $array2)) {
$array2[] = $val;
}
}
print_r($array2);
See codepad: http://codepad.org/X8jtnEkq
If you want to duplicates appended to the end of the array, after the script above, use array_merge($array2, $array);
:
<?php
$array = array(1900,1900,2000);
$array2 = array();
foreach ($array as $key => $val) {
if (!in_array($val, $array2)) {
$array2[] = $val;
unset($array[$key]);
}
}
$array = array_merge($array2, $array);
print_r($array);
Demo http://codepad.org/tRC6P2Go
Upvotes: 1
Reputation: 9398
you can use array_unique
http://php.net/manual/en/function.array-unique.php
to extract unique records and then array_diff to extract duplicate records
Upvotes: 1
Reputation: 6106
You could use array_unique to get unique results and then do an array_diff between the initial and the uniquified array to get the ids that are doubled to use them for a sql-query to tidy that table:
$uniquified = array_unique($initalResults);
$diff = array_diff($initalResults, $uniquified);
Upvotes: 1