Last active
August 29, 2015 14:20
-
-
Save touqeershafi/bf89351f3b226aae1a29 to your computer and use it in GitHub Desktop.
Country Hierarchy Maker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$data['USA'] = ['Alabama' => ['Montgomery','Birmingham'],'Arizona' => ['Phoenix','Mesa','Gilbert','Bonn']]; | |
$data['Germany'] = ['West Germany' => ['Bonn','Cologne']]; | |
$data['Canada'] = ['West Germany' => ['Bonn','Cologne']]; | |
function getHierarchy($location, $data, $start = 0){ | |
$totalCountries = count($data); | |
//Get Array Keys of rows eg countries. | |
$keys = array_keys($data); | |
$hierarchy = []; | |
$break = false; | |
//Loop Through Countries | |
for($i = $start; $i < $totalCountries; $i++){ | |
//If we have found the country then return it. | |
if($location == $keys[$i]) return [$keys[$i]]; | |
$hierarchy[] = $keys[$i]; | |
foreach($data[$keys[$i]] as $city => $places){ | |
// if we have found the city then return it with country. | |
if($city == $location){ | |
$hierarchy[] = $city; | |
$break = true; | |
break; | |
} | |
// if we have found the place in our places array then return it with country -> city -> place. | |
if(in_array($location, $places)){ | |
$hierarchy[] = $city; | |
$hierarchy[] = $location; | |
$break = true; | |
} | |
} | |
// Reset Hirarcy if we do not found our location in previews country. | |
if(!$break){ | |
$hierarchy = []; | |
} else { | |
break; | |
} | |
} | |
if($i < $totalCountries){ | |
$after = getHierarchy($location, $data, ($i+1)); | |
if(!empty($after)){ | |
array_unshift($after, $hierarchy); | |
return $after; | |
} else { | |
return [$hierarchy]; | |
} | |
} | |
return ![$hierarchy]; | |
} | |
$found = getHierarchy('Mesa', $data); | |
echo '<pre>'.print_r($found,1).'</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment