gpt4 book ai didi

php - 通过 PHP 从目录中随机化照片

转载 作者:行者123 更新时间:2023-12-04 04:34:34 25 4
gpt4 key购买 nike

我有以下功能代码,每次单击刷新按钮时,它都会随机化我在“照片”文件夹中的照片。我知道这可能不是最有效的编码方式,但就我而言,它是有效的。我正在寻求有关我的 PHP 代码的帮助,这将使照片更加随机。我目前在文件夹中有 200 多张图片,并且经常得到比我想要的更多的重复图片。我可以对其进行哪些更改? (PS. 忽略我正在玩的 AJAX/JavaScript)

<html> 

<head>
<title>Pictures!</title>
<style type="text/css">
body{ background-color:D3DFDE; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<div id='main'>
<?php
function randomimages(){
$dirname = isset($_REQUEST['dir'])? $_REQUEST['dir'] : './photos/';
$numimages = isset($_REQUEST['num'])? $_REQUEST['num'] : 1;
$pattern = '#\.(jpg|jpeg|png|gif|bmp)$#i';
$files = array();
if($handle = opendir($dirname)){
while(($file = readdir($handle)) !== false){
if(preg_match($pattern, $file)){
array_push($files, "<center><img src='" . $dirname . $file . "' alt='' /></br><br/><hr/></center>");
}
}
closedir($handle);
shuffle($files);
}
return implode("<center><br/>", array_slice($files, 0, $numimages)) . "<br/> </center>";
}
?>
<!-- <center><a id="myButton" href="#">MAS PICTURES!</a></center> -->
<center><input type='button' onClick='window.location.reload(true)' value='MAS PICTURES!!!' style="height:200px; width:150px" /></center>
<hr/>
<script type="text/javascript">
$(function() {
$("#myButton").click(function() {
$("#main").load("index.php");
});
});
</script>
<?php echo randomimages(); ?>
<center>Created by: Matt & Joe</center>
</div>


</body>
</html>

最佳答案

您可以执行以下操作:

  • 通过不一遍又一遍地读取目录来优化代码。您可以通过读取一次目录来执行此操作(然后将条目作为数组存储在 APC 缓存中)。为这个 APC 键设置一个超时时间以偶尔破坏缓存。
  • 调用 `mt_rand` 函数,min 为 `0`,max 为 `count(array)-1` 并访问该索引。

  • 从目录中读取的通用代码可以如下(需要修改以满足您的需求):
    <?php
    function &list_directory($dirpath) {
    if (!is_dir($dirpath) || !is_readable($dirpath)) {
    error_log(__FUNCTION__ . ": Argument should be a path to valid, readable directory (" . var_export($dirpath, true) . " provided)");
    return null;
    }
    $paths = array();
    $dir = realpath($dirpath);
    $dh = opendir($dir);
    while (false !== ($f = readdir($dh))) {
    if (strpos("$f", '.') !== 0) { // Ignore ones starting with '.'
    $paths[] = "$dir/$f";
    }
    }
    closedir($dh);
    return $paths;
    }

    关于php - 通过 PHP 从目录中随机化照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971188/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com