0

主要的PHP初学者在这里!我想从一个目录中获取所有图像,排除任何非 .jpg 文件,随机播放结果,然后显示字符串。最终它将被合并到某种幻灯片中。一切都很好,直到我试图改变结果。我没有输出,只是一个空白屏幕。

<?php
$rootpath = 'images/slide/';
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath));
foreach($fileinfos as $pathnames => $fileinfo) {
shuffle($pathnames);
foreach ($pathnames as $pathname) {
    if (preg_match("/^.*\.(lck|bak|swf|mno|png|php)$/i", $pathname)) {
        } else {
            echo $pathname. "<br />";
                }
        }
} 

?>

解决方案!!感谢所有的帮助,这让我自己的事情变得更加困难。

<?php
$rootpath = 'images/slide/';
$pathnames = scandir($rootpath);
shuffle($pathnames);
foreach ($pathnames as $pathname) {
if (preg_match("/^.*\.(lck|bak|swf|mno|png|php)$/i", $pathname)) {
    } else {
        print_r($pathname);
         }
}

?>

4

3 回答 3

1

如果 $pathnames 真的如您所说的那样是一个字符串,那么它工作得很好。访问http://writecodeonline.com/php/,将下面的代码粘贴到文本区域,然后多次点击“运行代码”。注意它们是如何正确随机化的。

还有什么问题……

$pathnames = "images/slide/IMG_2747.JPG images/slide/100_0547.JPG images/slide/IMG_6039.JPG images/slide/IMG_2188.JPG images/slide/IMG_1114.JPG images/slide/IMG_2135.JPG images/slide/IMG_8990.JPG images/slide/DSCN4634.JPG images/slide/IMG_0739.JPG images/slide/IMG_5145.JPG";
$splitpathnames = explode(" ", $pathnames);
shuffle($splitpathnames);
foreach ($splitpathnames as $pathname) {
if (!preg_match("/^.*\.(lck|bak|swf|mno|png|php)$/i", $pathname)) {

        echo $pathname. "<br />";
     }
 }
于 2013-08-30T20:42:53.750 回答
0

You can sort an array representation of an object but not an object in itself since it has no order of attributes.Try this?

<?php
    $rootpath = 'images/slide/';
    $fileinfos = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootpath));

      foreach($fileinfos as $pathnames => $fileinfo) {
        if (!$fileinfo->isFile()) continue;
          if (preg_match("/^.*\.(lck|bak|swf|mno|png|php)$/i", $pathnames)) {
        } else {
                    $arr = (array)$pathnames;
                    shuffle($arr);

               foreach($arr as $pics){
                  print "<img src =  " . $pics . " />";
              }


           }

        }

?>
于 2013-08-30T20:24:30.543 回答
0

根据您的评论, $pathnames 不是数组。您必须首先根据字符串生成一个数组,然后对其进行洗牌:

$pathnamesArray = explode(" ", $pathnames);
shuffle($pathnamesArray);
foreach ($pathnamesArray as $pathname) {        
    if (!preg_match("/^.*\.(lck|bak|swf|mno|png|php)$/i", $pathname)) {                  
         echo $pathname;
    }  
 }
于 2013-08-30T19:58:39.437 回答