简体   繁体   中英

PHP: Select Random Files

I am trying to make an android app where the users can vote the photos, with PHP creating a XML file for app, so the application can read all file list and can show but the problem is that with php ,I cannot choose only two random files (2 photos) from directory and make a list of this 2 selected file in XML .

Thank you

只需将文件读入一个数组( glob() ),将其shuffleshuffle ),然后将前两个切片( array_slice() )。

There isn't enough information for us to give accurate answers.

If you want the PHP to get only two random files then you can read the list into an array, and shuffle, or use a loop to grab two random objects.

$arrayList = array();

for($i=0; $i<1; $i++) {
   // will pick a random number between 0 and the maximum number in array
   // when populating the array, put an if statement that if it is in the xml
   // do not add to array
   $x = rand(0, count($arrayList));

   // do something with $x and remove it from the array or put an if statement
   // in this for loop so it will check if it pulled the same item, if so
   // then $i--; and let it loop until it finds another (not really recommended)
}

This isn't the most elegant way, but it will get the job done. Again, just not enough information to give the best answers. If you are using a SQL database, then can just pull from there with randomness.

i don't know if it's the best solution but i followed your suggestion and i did this and it's working as i wish. but is it the optimum solution ?

$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]", ""); 

then im taking output in xml format.

thank you for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM