-1

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.

Premox
  • 323
  • 10
  • 25
  • You need to show what you have tried.. but ultimately its most likely a dupe of [PHP Sort Array By SubArray Value](https://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value) or [PHP sort array alphabetically using a subarray value](https://stackoverflow.com/questions/10484607/php-sort-array-alphabetically-using-a-subarray-value/10484863) +3k [others](https://www.google.com/search?q=php+sort+multidimensional+array+by+value+alphabetically+site:stackoverflow.com) – Lawrence Cherone Oct 16 '20 at 16:18

1 Answers1

1

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:\r\n<pre>" . print_r($c, true) . "</pre>";
usort($c, "cmp");
echo "After Sorting:\r\n<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;
}

?>
Nyamul
  • 76
  • 4