Sorting JSON/Array in alphabetical order using multiple values in jQuery or PHP

I have the following problem: As you can see on the picture, I have a drop down box that is not sorted alphabetically by country or city.

The JSON object looks like this:

[{"HAM": {Name: "Hamburg", Country: "Germany", ...}, 
   "DEL": {Name: "Delhi", Country: "India", ...}, etc.}]

In PHP it is assembled inside a loop as follows:

$locations[$locationCode] = [
                'name' => $locationName,
                'type' => $locationObject->getType(),
                country' => $this->getCountryForLocation($locationName),
                'accessSizes' => $accessSizes,
                'services' => $services
        ]

How can I sort the countries alphabetically first and then the cities in jQuery or PHP? I would prefer to do this in PHP.

My problem is that I try it outside the loop and so I don’t know the $locationCode anymore. Can anyone help me? I tried array_multisort() to bypass the $locationCode but unfortunately it never worked.

Answer

PHP has two neat array sorting functions called usort and uasort (use this if you want to preserve the keys) either of which allows you to write custom functions to sort arrays any way you like.

<?php

$c = array();
$c["HAL"] = array("City" => "Hamlet", "Country" => "USA");
$c["HUS"] = array("City" => "Houston", "Country" => "USA");
$c["HAN"] = array("City" => "Hannover", "Country" => "Germany");
$c["HAM"] = array("City" => "Hamburg", "Country" => "Germany");

echo "Before Sorting:rn<pre>" . print_r($c, true) . "</pre>";
usort($c, "cmp");
echo "After Sorting:rn<pre>" . print_r($c, true) . "</pre>";

function cmp ($a, $b) {
    $cmp = strcmp($a["Country"], $b["Country"]);
    if ($cmp == 0) $cmp = strcmp($a["City"], $b["City"]);
    return $cmp;
}

?>