在jQuery或PHP中使用多个值按字母顺序对JSON/Array进行排序



我有以下问题:正如你在图片上看到的,我有一个下拉框,它不是按国家或城市的字母顺序排列的。

JSON object看起来像这样:

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

PHP中,它被组装在一个环路内,如下所示:

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

如何先按字母顺序对国家/地区进行排序,然后按jQueryPHP中的城市进行排序?我更愿意在PHP中这样做。

我的问题是我在循环之外尝试,所以我不再知道$locationCode了。有人能帮我吗?我试着用array_multisort()绕过$locationCode,但不幸的是,它从未起作用。

PHP有两个整洁的数组排序函数,分别称为usort和uasort(如果您想保留键,请使用这两个函数(,这两个功能都允许您编写自定义函数,以任何方式对数组进行排序。

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

最新更新