2012-12-20 229 views
0

我想按鍵排序關聯數組。我使用kso​​rt函數,但返回1而不是array.Below是我的代碼。按鍵排序關聯數組

$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

+0

不知道函數應該如何工作:閱讀[在手冊中](http://php.net/ksort)! –

+2

'ksort($ states)''而不是'$ states = ksort($ states)' –

+0

@ÁlvaroG.Vicario好的我知道了 –

回答

0

不要reaffect 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 here

+0

好的謝謝你的回答。 –

0

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

*排序函數直接改變數組。

0

使用ksort()通過數組排序的鍵

不分配結果。嘗試在排序後按以下方式打印:

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