【发布时间】:2015-05-24 14:50:16
【问题描述】:
我有一个关于 php 包含的问题。这是我现有的代码。
<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php");
$rand = array_rand($files);
include ($files[$rand]);
?>
这个代码实际上对我来说效果很好,因为内容是随机显示的。但是,我想得到更好的东西。因为,通过使用这段代码,每次我添加了content5.php、content6.php 等新内容时,我都不得不费心更新上面的代码以使新的content.php 出现。
我有什么解决方案,每次我添加一个新的content.php 并且新的content.php 在添加时自动出现时不要打扰上面的代码?有可能吗?
更新:新测试代码(再次测试失败,部分页面丢失)
<?php
$sDirectory = 'myfolder';
if( is_dir( $sDirectory ) )
{
$rDir = opendir( $sDirectory );
while( ( $sFile = readdir( $rDir ) ) !== FALSE )
{
if( ( $sFile == '.' ) || ( $sFile === '..' ) )
{
continue;
}
$aFiles[] = $sDirectory . '/' . $sFile;
}
}
$sRandom = array_rand( $aFiles );
require_once( $aFiles[ $sRandom ] );
?>
【问题讨论】:
-
因为你必须动态更新 $files 数组,没有足够的代码继续,你只是硬编码了 content1.php,content2.php,......你不是动态获取它,那你怎么能在那里添加新的 content.php 呢?
-
$sDirectory = 'myfolder/';应该是 $sDirectory = 'myfolder';因为目录分隔符已经附加在 $sDirectory 和 $sFile 之间。或者只是删除底部的。
-
我又更新了。但是,它似乎不起作用。我的部分页面丢失了。我想知道我实现的代码格式是否错误。
-
@AyyanarG,我不明白你想问什么。我正在寻找解决方案。希望我能用最好的解决方案解决这个问题。谢谢!
标签: php random include-path