OK, let's say when a user selects a country, they are also added with a "federation". These federations are pretty much region-centric.
Let's say I have something like this:
function getFedration($country_iso) {
// 6 federations
// afc = asian nations
// caf = african nations
// cocacaf = north & central america and Caribbean nations
// conmebol = south america
// ofc = Oceanian nations
// uefa = european nations
$afc = array("Japan", "China", "South Korea");
$caf = array("Cameroon", "Chad", "Ivory Coast");
$concacaf = array("United States" , "Canada", "Mexico");
$conmebol = array("Argetina", "Brazil", "Chile");
$ofc = array("Fiji", "New Zealand", "Samoa");
$uefa = array("Spain", "England", "Montenegro");
/*
PSEUDO-code
If $country_iso is in either of six arrays... mark that as the federation...
*/
return $federation;
}
I know, it says a country's name but when it comes down to it, it will be country's iso like JP instead of Japan, CN instead of China, et cetera.
So, I was wondering, is this a feasible thing or is there a better way you'd think?
How about putting all federations into an array, in order to loop through it? Makes things easier, like so:
function countryToFederation($country_iso) {
$federations = array(
"afc" => array("Japan", "China", "South Korea"),
"caf" => array("Cameroon", "Chad", "Ivory Coast"),
"concacaf" => array("United States" , "Canada", "Mexico"),
"conmebol" => array("Argetina", "Brazil", "Chile"),
"ofc" => array("Fiji", "New Zealand", "Samoa"),
"uefa" => array("Spain", "England", "Montenegro"),
);
foreach($federations as $federation) {
if(in_array($country_iso, $federation)) {
return $federation;
}
}
}
If a federation can only belong to one country, I would create one array instead:
$countryToFederationMap = array(
'Japan' => 'AFC',
'China' => 'AFC',
'Cameroon' => 'CAF',
// ...
);
Then the federation is simply:
return $countryToFederationMap[$country];
Related
I have to replace strings of multiple country names to their translations in another language. So I created an array of countries, where the keys are the countries in English and the values are the countries in the destination language...
So, let me first put a relevant extract of the array I used:
$countries = array(
//...
'Canada' => 'Καναδάς',
//...
'France' => 'Γαλλία',
//...
'Germany' => 'Γερμανία',
//...
'Korea' => 'Κορέα',
//...
'South Korea' => 'Νότια Κορέα',
//...
'United States' => 'Ηνωμένες Πολιτείες',
//...
'West Germany' => 'Δυτική Γερμανία',
//...
);
And the code I used is this:
$tmp[] = str_replace(array_keys($countries), $countries, $api->getCountry());
And below are two (special case) examples that are giving me a hard time figuring out how to deal with them...
West Germany • France
United States • Canada • South Korea
So the above two examples are replaced like this:
West Γερμανία • Γαλλία
Ηνωμένες Πολιτείες • Καναδάς • South Κορέα
I think it's very obvious what's happening here... The key Germany is found before the key West Germany, so str_replace replaces the Germany part with the translated name of it, and so West remains untranslated... The same happens with Korea, which (alphabetically) happens to be before South Korea...
Moving West Germany and South Korea above Germany and Korea fixes the problem, but this is not the proper way to deal with this I suppose, as it will happen to East Germany, and generally, any other country that has a two-word, etc...
What's the correct way to deal with this in your opinion? TIA
This is a little bit of a cheat but if you're going to use array_keys rather than a loop, you should just presort the countries array by length.
$keys = array_map('strlen', array_keys($countries));
array_multisort($keys, SORT_DESC, $countries);
$tmp[] = str_replace(array_keys($countries), $countries, $api->getCountry());
Here's a little example you can test at: https://www.tehplayground.com/uARSRel47jYICSIA
$countries = array(
'Canada' => 'Καναδάς',
'France' => 'Γαλλία',
'Germany' => 'Γερμανία',
'Korea' => 'Κορέα',
'South Korea' => 'Νότια Κορέα',
'United States' => 'Ηνωμένες Πολιτείες',
'West Germany' => 'Δυτική Γερμανία'
);
$keys = array_map('strlen', array_keys($countries));
array_multisort($keys, SORT_DESC, $countries);
echo str_replace(array_keys($countries), $countries, "West Germany"). "\n";
echo str_replace(array_keys($countries), $countries, "France") . "\n";
echo str_replace(array_keys($countries), $countries, "United States") . "\n";
echo str_replace(array_keys($countries), $countries, "Canada") . "\n";
echo str_replace(array_keys($countries), $countries, "South Korea") . "\n";
Output:
Δυτική Γερμανία
Γαλλία
Ηνωμένες Πολιτείες
Καναδάς
Νότια Κορέα
Update
As it turns out uksort takes care of this in one line:
uksort($countries,function($a, $b) { return strlen($b) > strlen($a);});
I found the same question but that's not very helpful because that is not working in many cases. So, I'm writing this question may be somebody have a better solution for it.
These are my addresses example.
[0] => "Skattkarr Varmland SE-65671" //Sweden
[1] => "Rayleigh , Essex SS6 8YJ" //UK
[2] => "Horgen, Zürich 8810" //Switzerland
[3] => "Edmonton Alberta T5A 2L8" //Canada
[4] => "REDDING, CA 96003" //USA
[5] => "New York, NY 96003" //USA
[6] => "New York NY 96003" //USA
I tried alot, but for many cases I'm getting failed.
I can pass 2 or 3 but I can't pass for all. Especially when the the country changes.
I tried to explode(" ",$addr[0]), it giving me the state on 0 and city on 1, but I try to use explode(" ",$addr[6]), It will give me New as a state and York as city. And same for UK and Canada zip code will be wrong.
My last question was marked duplicate, but my query is different and This question does not help me.
In order to separate these strings into state city and zipcode, you will need to define rules that can apply to all of your strings.
If we separate them by space, New York is not gonna work since New York is a city but has space in the middle.
If we separate them by comma, some of them don't have comma.
If we separate by both space and comma, we cannot assume the last item will be zipcode since T5A 2L8 is zipcode but will be separated.
So there is no rule that I can think of that would work with your data. You should start from how these strings can be separated and identified. Try to apply it to the code and we will gladly help you.
I tried to use OSM nominatim, to separate and validate data.
Request
https://nominatim.openstreetmap.org/search?format=json&limit=1&addressdetails=1&q=1088+Burton+Dr.+REDDING,+CA+96003+US
Response
[
{
"place_id": 266720693,
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_type": "way",
"osm_id": 10591437,
"boundingbox": [
"40.591203388592",
"40.591303388592",
"-122.34939939898",
"-122.34929939898"
],
"lat": "40.59125338859231",
"lon": "-122.34934939898274",
"display_name": "1088, Burton Drive, Lancer Hills Estates, Redding, Shasta County, California, 96003, United States",
"class": "place",
"type": "house",
"importance": 0.621,
"address": {
"house_number": "1088",
"road": "Burton Drive",
"neighbourhood": "Lancer Hills Estates",
"city": "Redding",
"county": "Shasta County",
"state": "California",
"postcode": "96003",
"country": "United States",
"country_code": "us"
}
}
]
And this what I actually want, breaking down of the address string.
I am querying the Wikipedia API. Normally I get the following, and I echo out the extract.
array:4 [▼
"pageid" => 13275
"ns" => 0
"title" => "Hungary"
"extract" => """
<p><span></span></p>\n
<p><b>Hungary</b> (<span><span>/<span><span title="/ˈ/ primary stress follows">ˈ</span><span title="'h' in 'hi'">h</span><span title="/ʌ/ short 'u' in 'bud'">ʌ</span><span title="/ŋ/ 'ng' in 'sing'">ŋ</span><span title="'g' in 'guy'">ɡ</span><span title="/ər/ 'er' in 'finger'">ər</span><span title="/i/ 'y' in 'happy'">i</span></span>/</span></span>; Hungarian: <span lang="hu"><i>Magyarország</i></span> <span title="Representation in the International Phonetic Alphabet (IPA)">[ˈmɒɟɒrorsaːɡ]</span>) is a parliamentary constitutional republic in Central Europe. It is situated in the Carpathian Basin and is bordered by Slovakia to the north, Romania to the east, Serbia to the south, Croatia to the southwest, Slovenia to the west, Austria to the northwest, and Ukraine to the northeast. The country's capital and largest city is Budapest. Hungary is a member of the European Union, NATO, the OECD, the Visegrád Group, and the Schengen Area. The official language is Hungarian, which is the most widely spoken non-Indo-European language in Europe.</p>\n
But if the entry does not exist in Wiki then I get this.
array:3 [▼
"ns" => 0
"title" => "Kisfelegyhaza"
"missing" => ""
]
So my question is how do I check if extract exists?
I tried the following but it does not work.
$wiki_array = The data received from Wiki
if (array_key_exists('extract',$wiki_array)){
// do something
}
$wiki_array = The data received from Wiki
if( isset($wiki_array['extract']) ){
// do something
}
isset($var) to check if that var is setted (so not null)
For anyone facing a the same problem, here is the solution I used.
foreach($wiki_array['query']['pages'] as $page){
if( isset($page['extract']) ){
echo '<p>';
echo $page['extract'];
echo '</p>';
}
}
I am trying to put together a geodetection for altering slight language variables.
I have the detection working perfectly, but the array check seems to not be working, I need to know if its from a list of countries. If I echo the country then I get the correct name so I know that parts working.
//Get User Country
$country_arr = array(
"Canada" => "ca",
"United States" => "us",
"United Kingdom" => "uk",
"Australia" => "au",
"South Africa" => "za",
"Unknow" => "shot"
);
$country=visitor_country();
if (in_array($country, $country_arr)) {
//include ("languages/" . $lang . ".php");
//echo $country_arr[$country];
echo "yes
";
} else {
//include ("languages/en.php");
echo "no
";
}
echo $country;
Have a functioning sandbox with all the related code working and edible http://sandbox.onlinephpfunctions.com/code/714d5105012f28cada695a6f11dc61516722e6d7
Also not working with a standard 1 dimensional array
$count_array = array("South Africa", "Unknow");
Use array array_key_exists in place of in_array
//Get User Country
$country = visitor_country();
$country_arr = array(
"Canada" => "ca",
"United States" => "us",
"United Kingdom" => "uk",
"Australia" => "au",
"South Africa" => "za",
"Unknown" => "shot"
);
//$count_array = array("South Africa", "Unknown");
if ( array_key_exists($country, $country_arr) ) {
//include ("languages/" . $lang . ".php");
//echo $country_arr[$country];
echo "yes<br>";
} else {
//include ("languages/en.php");
echo "no<br>";
}
echo $country;
For in_array function your $country_arr array should be like this
/* For IN Array */
$country_arr = array(
"Canada",
"United States",
"United Kingdom",
"Australia",
"South Africa",
"Unknown"
);
your $count_array = array("South Africa", "Unknow"); is not working because $country returns Unknown and you had Unknow that's not matching with with the value..
With in_array you check values not keys.
//Get User Country
$country_arr = array(
"Canada" => "ca",
"United States" => "us",
"United Kingdom" => "uk",
"Australia" => "au",
"South Africa" => "za",
"Unknow" => "shot"
);
$country = 'Canada';
if ( isset($country_arr[$country]) )
{
echo "yes";
}
else
{
echo "no";
}
echo "\n$country";
BTW
Keep in mind that PHP even with 'regular' arrays - without keys - have implicit keys so for in_array to work you would have to have:
$country_arr = array( "Canada", "United States", "United Kingdom" );
Above all countries have their keys (but implicit) so countries are values here. On your original code countries are keys.
You have a typo - Unknow / Unknown, also, you're not searching against keys with in_array(), you need to use array_key_exists() or array_flip($country_arr)
Your GeoIP service returns countryName and countryCode fields. Just use countryCode instead of countryName and your code will work:
if($ip_data && $ip_data->geoplugin_countryCode != null)
{
$result = $ip_data->geoplugin_countryCode;
}
I have an array of all the countries in the world as such:
$countries = array(
"GB" => "United Kingdom",
"US" => "United States",
"AF" => "Afghanistan",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua And Barbuda",
"AR" => "Argentina",
"AM" => "Armenia",
"AW" => "Aruba",
"AU" => "Australia",
"AT" => "Austria",
"AZ" => "Azerbaijan",
"BS" => "Bahamas",
"BH" => "Bahrain",
"BD" => "Bangladesh",
"BB" => "Barbados",
"BY" => "Belarus",
"BE" => "Belgium",
"BZ" => "Belize",
"BJ" => "Benin",
"BM" => "Bermuda",
"BT" => "Bhutan",
"BO" => "Bolivia",
"BA" => "Bosnia And Herzegowina",
"BW" => "Botswana",
"BV" => "Bouvet Island",);
And so on for all countries; I am 100% positive every country is listed properly.
I have an application form which stores the result in a file stored on the server. Currently the review page for the application is a basic text version and I am now in the process of putting it into a mock-form for my client to have a more visually appealing method of reviewing applications.
So an array named $in_data stores the results that come from the file. This array is structured as such "emergency_medical_insurance" => "value_user_entered". Each key is the name of the HTML element it came form and the value is what the user put in.
The country select list on the form returns a two-letter code of the country. So what I am trying to do is search $countries with the value of $in_data['country_select'] and then return the name of the country.
echo $in_data['country_select']; returns 'CA' the letter code for Canada and the test country I have entered.
echo $countries['CA']; returns 'Canada'
if (array_key_exists($in_data['country_select'], $countries)){
echo "Country Found";
}
else { echo "failed"; }
returns nothing.
if (array_key_exists('CA', $countries)){
echo "Country Found";
}
else { echo "failed"; }
Also returns nothing. And when I say nothing I mean nothing, not null, not true, not false; just doesn't even run.
My question is simple; how is the code below (taken from the offical PHP manual) which does EXACTLY the same thing my code does, working, but my code won't even return anything?
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
since you are reading from a file, you may be getting other characters, try trim():
if (array_key_exists(trim($in_data['country_select']), $countries)){
echo "Country Found";
}
else { echo "failed"; }
I had a similar problem while reading from a file.
The solution was to remove the BOM from the first line.
function remove_utf8_bom($text) {
$bom = pack('H*','EFBBBF');
$text = preg_replace("/$bom/", '', $text);
return $text;
}