        <?php

$locations = array ( 
    Array ( 
                    "L1ID" => 2 ,
                    "L1Location" => 'USA' ,
                    "L2ID" => 3 ,
                    "L2Location" => 'New York',
                    "L3ID" => 4 ,
                    "L3Location" => 'Manhanttan',
                ) ,
    Array (  
                    "L1ID" => 2 ,
                    "L1Location" => 'USA' ,
                    "L2ID" => 8 ,
                    "L2Location" => 'New Jersey' ,
                    "L3ID" => 7 ,
                    "L3Location" => 'Bergen County',
                ) ,
 
    Array ( 
                    "L1ID" => 5 ,
                    "L1Location" => 'Canada' ,
                    "L2ID" => 12,
                    "L2Location" => 'Ontario' ,
                    "L3ID" => 50,
                    "L3Location" => 'Toronto' ,
                ) ,
    Array ( 
                    "L1ID" => 6 ,
                    "L1Location" => 'South Korea',
                    "L2ID" => 22,
                    "L2Location" => 'Gyungido' ,
                    "L3ID" => 25,
                    "L3Location" => 'Buchon',
                ) ,
    );
            $countries = array();
            $states = array();
            $cities = array();
            foreach ($locations as $location) {
                if(!array_key_exists($location['L1ID'], $countries))
                    $countries[$location['L1ID']] = array(
                        'name' => $location['L1Location'],
                        'states' => array(),
                    );
                if(!array_key_exists($location['L2ID'], $countries[$location['L1ID']]['states'])){
                    $countries[$location['L1ID']]['states'][$location['L2ID']] = array(
                        'name' => $location['L2Location'],
                        'cities' => array(),
                    );
                }
                if(!array_key_exists($location['L3ID'], $countries[$location['L1ID']]['states'][$location['L2ID']])){
                    $countries[$location['L1ID']]['states'][$location['L2ID']]['cities'][$location['L3ID']] = $location['L3Location'];
                }
            }

            // Generate $countries box
            foreach ($countries as $key => $country) {
                echo ($key.'<BR>'."\n");
                echo '<option value="' . $key . '">' . $country['name'].'</option>'."\n";

                // Generate $states box
                foreach ($country['states'] as $key => $state) {
                    echo ($key.'<BR>'."\n");
                    echo '<option value="' . $key . '">' . $state['name'].'</option>'."\n";

                    // Generate $city box
                    foreach ($state['cities'] as $key => $city) {
                        echo ($key.'<BR>'."\n");
                        echo '<option value="' . $key . '">' . $city.'</option>'."\n";
                    }

                }

            }

        ?>
