在循环中跳过数组中的重复值

时间:2015-10-09 10:57:58

标签: php arrays loops if-statement

我有分类为已读和未读书籍的书籍序列号。 什么时候有读的书我把这个序列号后面的数据读入如下。

array(
"1234567890","read",
"2345678901","read",
"2345678901",
"2345678901",
"1234561231",
"3333333333","read",
"3333333333"
)

所有其他人的状态均未读 我的代码如下。

$scannedbook=array("0075423658","0012366321","read","0012366321","0012366321","0012366321","0132546874","read","0132546874");
$lenghtofarray = count($scannedbook);
$readbook = "0";
$unreadbook = "0";
for ($x = 0; $x <= $lenghtofarray-1; $x++) {
    if($scannedbook[$x] == 'read'){
        continue ;
    }
    if($scannedbook[$x+1] == 'read'){
        $readbook++;
        for($i=$x; $i<$lenghtofarray-1; $i++){
            if($scannedbook[$x] == $scannedbook[$i+1]){
             $unreadbook++;
            }
        }   
    }
    else{
        $unreadbook++;
    }
echo $scannedbook[$x]." readbook=".$readbook."unreadbook=".$unreadbook."<br />";
        $readbook = "0";
        $unreadbook = "0";
}

我的输出是

1234567890: 0 unread, 1 read 
2345678901: 2 unread, 1 read 
2345678901: 1 unread, 0 read 
2345678901: 1 unread, 0 read 
1234561231: 1 unread, 0 read 
3333333333: 1 unread, 1 read 
3333333333: 1 unread, 0 read 

我只需要跳过重复值的那些,如果它们已经像粗体值那样被检查为第3个4和7,并且需要这样的结果

    1234567890: 0 unread, 1 read
    2345678901: 2 unread, 1 read
    1234561231: 1 unread, 0 read
    3333333333: 1 unread, 1 read

3 个答案:

答案 0 :(得分:1)

在输出之前添加

if (!isset($arr[$readbook][$unreadbook])) {
    $arr[$readbook][$unreadbook] = 1;
} else {
   $readbook = "0";
   $unreadbook = "0";
   continue;
}

答案 1 :(得分:1)

您可以尝试使用PHP函数array_unique()从数组中删除重复值。 它的工作原理如下。

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

输出将是。

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

答案 2 :(得分:1)

试试这个

<?php
$scannedbook=array("0075423658","0012366321","read","0012366321","0012366321","0012366321","0132546874","read","0132546874");
$lenghtofarray = count($scannedbook);
$readbook = "0";
$unreadbook = "0";
$dummyArray=array();
for ($x = 0; $x <= $lenghtofarray-1; $x++) {
    if($scannedbook[$x] == 'read'){
        continue ;
    }
    if($scannedbook[$x+1] == 'read'){
        $readbook++;
        for($i=$x; $i<$lenghtofarray-1; $i++){
            if($scannedbook[$x] == $scannedbook[$i+1]){
             $unreadbook++;
            }
        }   
    }
    else{
        $unreadbook++;
    }
    if(!in_array($scannedbook[$x],$dummyArray))
    {
    echo $scannedbook[$x]." readbook=".$readbook."unreadbook=".$unreadbook."<br />";
    array_push($dummyArray,$scannedbook[$x]);
    }
        $readbook = "0";
        $unreadbook = "0";
}
?>