0

我想按键对关联数组进行排序。我使用 ksort 函数,但它返回 1 而不是数组。下面是我的代码。

$states=array( "DD"=>"Daman and Diu", "LD"=>"Lakshdweep", "DN"=>"Dadra
and nagar haveli", "AN"=>"Andaman and Nicobar island", "SK"=>"Sikkim",
"MZ"=>"Mizoram", "GA"=>"Goa", "PY"=>"Puduchery", "CH"=>"Chandigarh",
"ML"=>"Meghalaya", "AR"=>"Arunachal Pradesh", "TR"=>"Tripura",
"HP"=>"Himanchal Pradesh", "NL"=>"Nagaland", "PB"=>"Punjab",
"CG"=>"Chattisgarh", "JK"=>"Jammu and Kashmir", "UA"=>"Uttrakhand",
"HR"=>"Haryana", "JH"=>"Jharkhand", "KL"=>"Kerela", "MN"=>"Manipur" ,
"AS"=>"Assam", "RJ"=>"Rajasthan", "MP"=>"Madhya Pradesh",
"KA"=>"Karnataka", "BR"=>"Bihar", "OR"=>"Orissa", "GJ"=>"Gujrat",
"AP"=>"Andhra Pradesh", "TN"=>"TamilNadu", "DL"=>"Delhi",
"MH"=>"Maharastra", "WB"=>"WestBengal", "UP"=>"UttarPradesh",
); 


 $states = ksort($states);
 print_r($states);

我得到的输出是:1

我想要数组而不是 1。

4

3 回答 3

0

不要做$states = ksort($states);
ksort($states);

*sort 函数直接改变数组。

于 2012-12-20T11:10:04.687 回答
0

不要将 ksort 的结果重新影响到您的数组, ksort 通过引用获取一个数组:

$states=array(
"DD"=>"Daman and Diu", "LD"=>"Lakshdweep", "DN"=>"Dadra and nagar haveli", "AN"=>"Andaman and Nicobar island", "SK"=>"Sikkim", "MZ"=>"Mizoram", "GA"=>"Goa", "PY"=>"Puduchery", "CH"=>"Chandigarh", "ML"=>"Meghalaya", "AR"=>"Arunachal Pradesh", "TR"=>"Tripura", "HP"=>"Himanchal Pradesh", "NL"=>"Nagaland", "PB"=>"Punjab", "CG"=>"Chattisgarh", "JK"=>"Jammu and Kashmir", "UA"=>"Uttrakhand", "HR"=>"Haryana", "JH"=>"Jharkhand", "KL"=>"Kerela", "MN"=>"Manipur" , "AS"=>"Assam", "RJ"=>"Rajasthan", "MP"=>"Madhya Pradesh", "KA"=>"Karnataka", "BR"=>"Bihar", "OR"=>"Orissa", "GJ"=>"Gujrat", "AP"=>"Andhra Pradesh", "TN"=>"TamilNadu", "DL"=>"Delhi", "MH"=>"Maharastra", "WB"=>"WestBengal", "UP"=>"UttarPradesh"
    );

ksort($states);
print_r($states);

更多关于 ksort的信息在这里

于 2012-12-20T11:10:08.520 回答
0

使用ksort()按其键对数组进行排序

不要分配结果。排序后尝试打印如下,

ksort($states);
print_r($states);
于 2012-12-20T11:10:40.327 回答