我使用下面给出的链接中的相同脚本来显示目录中的文件。
Link list based on directory without file extension and hyphens in php
$directory = 'folder/';
$blacklist = array(
'index'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href=\"{$file}\">{$name}</a></li>";
}
}
上面的脚本显示文件夹中的所有文件(index.php除外)。但我只想显示五个随机文件。这可能吗?
答案 0 :(得分:0)
根据您的编辑,我认为这是您尝试做的事情?
<?php
// Get all files ending in .php in the directory
$rand_files = glob("*.php");
// If the string "index.php" is contained in these results, remove it
// array_search returns the key of the $needle parameter (or false) if not found
if (($location = array_search("index.php", $rand_files)) !== false) {
// If "index.php" was in the results, then delete it from the array using unset()
unset($rand_files[$location]);
}
// Randomly choose 5 of the remaining files:
foreach (array_rand($rand_files, 5) as $rand_index) {
$fname = $rand_files[$rand_index];
echo "<a href='$fname'>$fname</a>\n";
}
?>