What I want to do is to display 5 random images with text out of a certain number without repeating. The links to images and the texts are to be stored in the database. The issue I've run into is I need to put every ID value into the single PHP array in order to shuffle the IDs and pick random 5, yet I keep failing in combining them into a single array, if I have 3 rows I end up with 3 arrays.
This is an example of a failing code with 3 rows with ID 1,2,4:
function getAll () {
$query = mysql_query("SELECT * FROM ads") or die(mysql_error());
$myarray = array();
while ($numbers = mysql_fetch_array($query)){
$arr = $numbers['ID'].",";
print_r (explode(",", $arr));
}
};
This is the output:
Array ( [0] => 1 [1] => ) Array ( [0] => 2 [1] => ) Array ( [0] => 4 [1] => )
This is the desired output:
Array ( [0] => 1 [1] => 2 [2] => 4)
Guess it's a noob question but I've done my best in trying to find the solution and failed.
Easy solution: Shuffle the result directly by using ORDER BY RAND()
in your MySQL query:
SELECT * FROM ads ORDER BY RAND() LIMIT 5
I think you should look at Alp's solution, but to answer your question directly - put this in your while
loop.
array_push($arr,$numbers['Id']);
but first declare the variable before the loop:
$arr = array();
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.