Picking a random image out of different directories based on GEO locations

佐手、 提交于 2019-12-26 01:55: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?


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!