下面的代码将从命名文件夹中选择我的所有php文件,然后将它们随机播放并在我的页面上回显10个结果,该文件夹包含一个index.php文件,我希望将其从结果中排除。
<?php
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p><a href="../folder/'.$file.'">'.$title.'</a></p>';
}
}
?>
<?=$thelist?>
我找到了一个排除index.php的代码,但我不确定如何将其合并到我的代码中。
<?php
$random = array_values( preg_grep( '/^((?!index.php).)*$/', glob("../folder/*.php") ) );
$answer = $random[mt_rand(0, count($random) -1)];
include ($answer);
?>
答案 0 :(得分:2)
为什么不直接修改
if ($file != "." && $file != "..") {
到
if ($file != "." && $file != ".." && $file != 'index.php') {
答案 1 :(得分:1)
基于glob()而不是readdir()的方法:
<?php
$files = glob('../folder/*.php');
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
$file = basename($file);
if ($file == 'index.php') continue;
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
// ...
}
答案 2 :(得分:1)
您可以使用
$it = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$it = new RegexIterator($it, '/.php$/i', RegexIterator::MATCH);
$exclude = array("index.php");
foreach ( $it as $splFileInfo ) {
if (in_array($splFileInfo->getBasename(), $exclude))
continue;
// Do other stuff
}
或者只是
$files = array_filter(glob(__DIR__ . "/*.php"), function ($v) {
return false === strpos($v, 'index.php');
});
答案 3 :(得分:0)
您可以在阅读目录内容时将其排除(就像使用'。'和'..'一样):
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p><a href="../folder/'.$file.'">'.$title.'</a></p>';
}
}
?>
答案 4 :(得分:0)
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != 'index.php')
$fileTab[] = $file;
}
答案 5 :(得分:0)
您可以将此行if ($file != "." && $file != "..") {
更改为if ($file != "." && $file != ".." && $file != 'index.php') {
答案 6 :(得分:0)
您找到的代码取代了繁琐的目录读取循环。
它应该只是:
$files = preg_grep('~/index\.php$~', glob("../folder/*.php"), PREG_GREP_INVERT);
像以前一样获得10个元素:
$files = array_slice($files, 0, 10);
然后输出那些。