如何删除重复项并添加新的唯一文件?

How can I remove duplicates and add a new unique file?

我在我的网站上从目录中的所有文件中随机抓取 5 个文件,一切顺利,但大约 %50 的时间我得到了一个副本。我想: 1)删除重复项 2) 替换为新的唯一文件

.. 或者我可以更轻松地一起防止重复?我试图为此找到一个功能而不问这里的问题,但我没有找到一个。有任何想法吗?谢谢!!

 <?php 
 //define stuff
$dir = "uploads/";
$allfiles = array_diff(scandir($dir), array('.', '..'));
echo '<pre>';
print_r("all files ready for access");
echo '<pre>';

// create zip
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
    $error .= "* Sorry ZIP creation failed at this time";
}
else {
    echo '<pre>';
    print("created zip");
    echo '<pre>';
}

// array of random files    
$n=1;
while ($n<=6){
    $n ++;
    $file = array_rand($allfiles);
    $randomfile = $allfiles[$file];
    echo '<pre>';
    print_r($randomfile);
    echo '<pre>';
if (file_exists($dir.$randomfile)) {
    $content = $dir.$randomfile;
    echo '<pre>';
    print_r($content);
    echo '<pre>';
    $zip->addfile($content,$randomfile);
    echo 'ok';
} else {
    echo 'failed';
}
}

//present for download
$zip->close();
ob_get_clean();
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=" . basename($zip_name) . ";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($zip_name));
    readfile($zip_name);
  if(file_exists($zip_name))
{
  unlink('zipfile.zip');
}

?>

请检查您是否已经找到该文件。如果您已经找到它,请通过继续而不增加 $n.

来获得一个新的

看看这个:

// array of random files    
$n = 1;
$myfiles = [];
while ($n<=6){
    $file = array_rand($allfiles);
    $randomfile = $allfiles[$file];
    if(!in_array($randomfile, $myfiles)) { // this line checks if you already got this file
        $myfiles[] = $randomfile;
    } else {
        continue; // if you already got it, continue (http://php.net/manual/de/control-structures.continue.php)
    }
    echo '<pre>';
    print_r($randomfile);
    echo '<pre>';
    if (file_exists($dir.$randomfile)) {
        $content = $dir.$randomfile;
        echo '<pre>';
        print_r($content);
        echo '<pre>';
        $zip->addfile($content,$randomfile);
        echo 'ok';
    } else {
        echo 'failed';
    }
    $n++; // increment in the end
}

您可以将第二个参数传递给 array_rand 函数:

$my_files = array_rand($allfiles, 5);

或打乱数组并获取 - 例如 - 前五项:

shuffle($allfiles);
// now $allfiles[0...4] are 5 different files.

为已经添加到 zip 中的文件创建一个数组:

$added = //array
$zip->addfile($content,$randomfile);
array_push($added,$randomfile)

并在插入之前检查上述数组中的任何新文件:

if(!in_array($randomfile, $added)){
  //add the file to zip
}