Randomize Array然后在foreach循环中检索

时间:2014-02-20 21:12:37

标签: php arrays shuffle

我正在尝试随机输出数组的值,因此它们的显示方式没有顺序。它工作,而不是预期的。

它们仍然按照它们在数组中列出的顺序显示,所以我必须遗漏一些东西..

    $itemArray = array("item1.php", "item2.php", "item3.php");
        shuffle($itemArray); 

        foreach ($itemArray as $item) {
                    shuffle($itemArray); 

                    include($itemArray[0]);

                }

我应该使用rand_array吗?

3 个答案:

答案 0 :(得分:2)

foreach内,变量$item包含当前项目,因此它看起来像:

foreach($itemArray as $item) {
    include($item);
}

不确定以随机顺序包含文件的原因是什么......

答案 1 :(得分:0)

没有必要在你的foreach里再次洗牌。

$itemArray = array("item1.php", "item2.php", "item3.php");
shuffle($itemArray); 

foreach ($itemArray as $item) {
     include($item);
}

阅读文档以正确使用foreach: http://www.php.net/manual/en/control-structures.foreach.php

答案 2 :(得分:0)

这就足够了:

$itemArray = array("item1.php", "item2.php", "item3.php");
shuffle($itemArray); 

foreach ($itemArray as $item) {
    include($item);
}
  1. shuffle()将数组随机化,多次调用它是不必要的,可能会导致重复或省略项目。
  2. 您正在遍历$itemArray中的元素,但是每次迭代都会重复包含$itemArray[0]而不是当前项目。