-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.

1

1 Answer 1

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;
}

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.