Reputation:
I was wondering if it's possible to get a sequence of pictures into an array. I'd like to use JavaScript if possible, if not can it be possible with PHP and how?
So I created a map called "images/cars", which contains a lot of images. All the pictures have a different name. One is called: "audi", another one is called: "mercedes" and so on. They all are the same type (.gif
).
I can do this manually like:
var pictures = ["audi.gif", "mercedes.gif", "aston martin.gif", ....]
// and so on
But that is too much work. Also, when I upload a new picture to the "images" folder, I have to manually add the new image to the array.
Here is my full code :
<!DOCTYPE html>
<html>
<head>
<script>
var cars= ["audi.gif", "mercedes.gif", "aston martin.gif", "bmw.gif", "ferrari.gif"];
var outputRandomImage = "";
function myFunction() {
for (var i = cars.length - 1; i >=0; i--) {
var random = Math.floor(Math.random()*(i+1));
var randomImage = cars[random];
cars[random] = cars[i];
cars[i] = randomImage;
outputRandomImage += '<img src="images/cars/' + randomImage + '">' + "<br>";
document.getElementById("output").innerHTML = outputRandomImage;
}
}
</script>
</head>
<body onload="myFunction()">
<p id="output"></p>
</body>
</html>
Hope someone here could help. I'm open to any ideas, recommendations, and suggestions. Thank you.
Upvotes: 0
Views: 1213
Reputation: 191
One way is to create another PHP page
$folder = "."; // folder with the image files
$scan = scandir($folder);
$files = [];
foreach($scan as $file_name)
{
if (!is_dir("$folder/$file_name"))
{
$array_push($files, $file_name) // if it is not a directory add it to the files list
}
}
$json_string = json_encode($ar);
echo $json_string;
And for the javascript
$.post("getCars.php", function(data, status){
if(status==="success"){
cars = JSON.parse(data)
}
});
Upvotes: 1