2

如何检查下一行是否重复。如果重复,它将移动到下一行。

例子:

1st row: 1900
2nd row: 1900
3rd row: 2000

mysql和php怎么能做到这些结果:

1st row: 1900
2nd row: 2000
3rd row: 1900

这是可能的还是任何可能的代码?

<?php
$array   =  array(1900,1900,2000);

$checkDuplicates = array_diff($array);

print_r($checkDuplicates);

?>

接下来如何移动重复的行?

4

5 回答 5

2

您可以将最后一行存储在临时变量 $last 中,并在 foreach 循环中执行以下操作:

$last = '';
foreach ($array as $row){
    if ($row== $last){
        continue;
    } else {
        $returnArray[] = $row;
    }
    $last = $row;
}
var_dump($returnArray);
于 2013-09-24T09:50:32.213 回答
1

您可以使用array_unique来获得唯一的结果,然后在初始数组和唯一数组之间执行array_diff以获取加倍的 id 以将它们用于 sql 查询以整理该表:

$uniquified = array_unique($initalResults);
$diff = array_diff($initalResults, $uniquified);
于 2013-09-24T09:52:09.983 回答
1

您需要堆叠具有唯一值的第二个数组。

<?php
$array   =  array(1900,1900,2000);
$array2  =  array();

foreach ($array as $val) {
    if (!in_array($val, $array2)) {
        $array2[] = $val;
    }
}

print_r($array2);

见键盘:http ://codepad.org/X8jtnEkq

如果要复制附加到数组末尾的副本,请在上面的脚本之后使用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);

演示http://codepad.org/tRC6P2Go

于 2013-09-24T09:49:34.930 回答
1

你可以使用 array_unique

http://php.net/manual/en/function.array-unique.php

提取唯一记录,然后 array_diff 提取重复记录

于 2013-09-24T09:54:22.223 回答
0

这个问题是初等编程,在大学的第一周你通常会遇到这样的问题。

array_diff 不会帮助你,它比较两个不同的数组,而你正在寻找一个数组中前一个元素的比较。

无论是来自 mysql 还是数组,同样的原则都适用。

另外,问自己一个问题,是否需要先对这些数据进行排序?

尝试这个

<?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] ; 

}


?>

上面代码的输出是..

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 ?

确定动作是否发生在第一个条目上很简单,检查 $i 的值

于 2013-09-24T10:04:48.063 回答