【问题标题】:Load in multiple random .html files with PHP [closed]使用 PHP 加载多个随机 .html 文件 [关闭]
【发布时间】:2013-10-02 17:39:14
【问题描述】:

我有 6 个 html 文件(test1.html、test2.html、test3.html 等),我希望其中 3 个随机显示且不重复。然后每次加载网页时都会使用不同的顺序和文件。

说:test1.html、test4.html、test2.html

或者:test5.html、test2.html、test3.html

或者:test3.html、test6.html、test2.html

等等......没有重复

我从上一个问题中得到了这个 php 代码,这是一个好的开始。它只包含 1 个我需要 3 个的 html 文件?

<?php
$files = glob('*.html');
$random_file = $files[array_rand($files)];
include($random_file);
?>

Load in random .html file with PHP?

非常感谢任何帮助,谢谢。

【问题讨论】:

  • 抱歉,您需要学习基本编程。如果你想要 3 个文件,那么你必须做 3 次。你如何去做取决于你......对array_rand的3次调用,或者一个迭代3次的循环。
  • 今天最好的 3 个建议词:谷歌“随机文件 php”/实际上这更像是四个,但谁在数(?)
  • 如果我回答了你的问题,你能接受吗
  • +1 因为该操作已投入研究工作

标签: php html select random no-duplicates


【解决方案1】:

根据您上面的示例。

$i = 0;
while($i < 3) {

    $randInt = rand(1, 6);
    if(isset($used)) {
        while($a < 1) {
            if(array_search($randInt, $used)) {
                $a++;
            } else {
                $randInt = rand(1, 6);
                continue;
            }
        }
    }
    include_once("path/to/test$randInt.html");
    $used[] = $randInt;
$i++;
}

基于 AD7six 的想法,这更加简洁,并且还允许使用非数字文件名:

$files = array(
    1=>'file_foo.html',
    2=>'file2_bar.html',
    3=>'file3_make.html',
    4=>'file4_it.html',
    5=>'file5_more.html',
    6=>'file6_succinct.html');

shuffle($files);

for($i=0;$i<3;$i++) {
    include_once("path/to/$files[$i]");
}

【讨论】:

  • 当我在我的服务器“include_once('test$randInt.html');”上测试文件时,我是一个 php 新手php 代码正在寻找一个名为“test$randInt.html”的文件,而不是 file1.html 到 file6.html。代码有问题吗?
  • 查看我的更新,我应该用双引号括起来。对不起。 php.net/manual/en/language.types.string.php
  • 这段代码比要求的要多得多。例如,带有随机播放和数组弹出的循环更易于读取、执行和调试。
  • @MartynGray 添加 $i++;到循环结束。 AD7six 不要迷惑他 ;)
  • 感谢保持基本,这让我更容易理解。我可以看到 '$i' 在代码顶部有 3 个设置。但是底部的“$i++”循环似乎在我的服务器上不起作用,因为我只得到 1 个 test.html 文件。这是我的 php 文件的链接enzygo.com/temp/index.php
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多