问题
The code for picking an random image out of a directory is pretty straight forward.
For example; my current code is this:
<?php
$imagesDir = 'img/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)]; // See comments
?>
I want to use Cloudflare's GEO IP finder, so when the user visits the website it feeds back where the users from.
So let's say I want,
if england use directory > img/en/
if australia use directory > img/au/
if USA use directory > img/usa/
if NZ use directory > img/nz/
if any other country > img/
I know the logic to it, but putting it into code is another thing which i've been struggling to do.
Any ideas?
回答1:
Create an array of the location directories and their corresponding names then build your image directory based on the geo location ($location
in my example).
$location = 'australia';
$dirs = array('england' => 'en',
'australia' => 'au',
'USA' => 'usa',
'NZ' => 'nz');
$imagesDir = 'img/' . (isset($dirs[$location]) ? $dirs[$location] . '/' : '');
If a location is not found in the array the setting of the $imagesDir
variable will default to img/
as it is now.
回答2:
Essentially, you are just trying to convert "england" -> img/en/ Any straight conversion, like this, I like to use a dictionary/map (depending on the language), or associative arrays for PHP. Uses a ternary, if the key (country) is not in the array, then "img/"
$arr = [
"england" => "img/en/",
//...
];
$imagesDir = in_array($COUNTRY, $arr) ? $arr[$COUNTRY] : "img/";
来源:https://stackoverflow.com/questions/51212132/picking-a-random-image-out-of-different-directories-based-on-geo-locations