PHP:选择随机文件

PHP:选择随机文件,php,xml,random,Php,Xml,Random,我正在尝试制作一个android应用程序,用户可以对照片进行投票,PHP为应用程序创建一个XML文件,这样应用程序可以读取所有文件列表并显示,但问题是使用PHP,我不能选择只有两个随机文件(2张照片)从目录中,在XML中列出这2个选定文件 谢谢只需将文件读入一个数组(glob()),将其洗牌(shuffle),然后切掉前两个(array\u slice())即可。没有足够的信息让我们给出准确的答案 如果希望PHP只获取两个随机文件,那么可以将列表读入数组,然后进行洗牌,或者使用循环获取两个随机对

我正在尝试制作一个android应用程序,用户可以对照片进行投票,
PHP
为应用程序创建一个
XML
文件,这样应用程序可以读取所有文件列表并显示,但问题是使用
PHP
,我不能选择只有两个随机文件(2张照片)从目录中,在
XML
中列出这2个选定文件


谢谢

只需将文件读入一个数组(
glob()
),将其洗牌(
shuffle
),然后切掉前两个(
array\u slice()
)即可。

没有足够的信息让我们给出准确的答案

如果希望PHP只获取两个随机文件,那么可以将列表读入数组,然后进行洗牌,或者使用循环获取两个随机对象

$arrayList=array()


对于($i=0;$i我不知道这是否是最好的解决方案,但我遵循了你的建议,我这样做了,而且效果如我所愿。但这是最佳解决方案吗

$myfeed = new RSSFeed();    


$dir = opendir ("./"); 
$i = 0;
while(false !=($file = readdir($dir))){
if (strpos($file, '.jpg',1)||strpos($file, '.jpeg',1)||strpos($file, '.png',1) ) { 
    $images[$i]= $file;
    $i++;
    }
}
$random_img=rand(2,count($images)-1);
$random_img1=rand(2,count($images)-1);

$myfeed->SetItem("http://myhost.c o m/images/$images[$random_img]", "$images[$random_img]", ""); 
$myfeed->SetItem("http://myhost. co m/images/$images[$random_img1]", "$images[$random_img1]", ""); 
然后我以
xml
格式获取输出


谢谢您的帮助。

您需要添加一个防护,这样同一个项目就不会被拾取两次。我喜欢这种任务——尽管对于大型(或非物化)数据集,提前终止洗牌算法可能更合适。
$myfeed = new RSSFeed();    


$dir = opendir ("./"); 
$i = 0;
while(false !=($file = readdir($dir))){
if (strpos($file, '.jpg',1)||strpos($file, '.jpeg',1)||strpos($file, '.png',1) ) { 
    $images[$i]= $file;
    $i++;
    }
}
$random_img=rand(2,count($images)-1);
$random_img1=rand(2,count($images)-1);

$myfeed->SetItem("http://myhost.c o m/images/$images[$random_img]", "$images[$random_img]", ""); 
$myfeed->SetItem("http://myhost. co m/images/$images[$random_img1]", "$images[$random_img1]", "");