Picking a random image out of different directorie

2019-09-20 22:55发布

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?

2条回答
虎瘦雄心在
2楼-- · 2019-09-20 23:05

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.

查看更多
别忘想泡老子
3楼-- · 2019-09-20 23:26

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/";
查看更多
登录 后发表回答