【问题标题】:Include php file randomly随机包含php文件
【发布时间】: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.phpcontent6.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


【解决方案1】:
$sDirectory     = 'includes';
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 ] );

【讨论】:

  • 嗨@Vladimir Ramik,感谢您的及时回答!我试过你的代码。但是,它不起作用。我想知道我是否错误地将代码放置在我的网站上?您能否提供正确的代码或进一步的解释?我还是 php 编码的新手。谢谢!
  • 错过了底部的随机位。固定。
  • 嗨@Vladmir Ramik,我已经用你的代码更新了我的问题。这是在我的网站上实现代码的方式吗?但是,它测试失败了。有什么问题吗?
  • 你有 2 /s 'myfolder/' 和 $aFiles[] = $sDirectory 。 '/' 。 $s文件;
  • 对不起!我不明白。请您修改我的问题或您的答案中的代码,以便我知道出了什么问题?我是 php 编码的新手。谢谢! :)
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 2011-08-02
  • 2012-02-13
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多