2011-02-25 28 views
0

我想我的排序數組,我不斷收到的1PHP排序assocative

這裏結果是代碼的請求幫助

  $foo = array(
       2 => "Sports", 
       40 => "Parent and Families", 
       43 => "Arts and Entertainment", 
      ); 
      $foo = sort($foo); 

我希望他們通過價值

排序

回答

5

Sort不返回排序的數組。它在成功時返回FALSE的TRUE。該數組通過引用傳遞。所以調用該方法,只是用它

$foo = array(
       2 => "Sports", 
       40 => "Parent and Families", 
       43 => "Arts and Entertainment", 
      ); 
      sort($foo); //foo is now sorted 

編輯

不過請注意,那種()實際上重新分配你的指數。您應該使用asort()而不是那種,如果你想保持協會

+0

謝謝!讓我瘋狂 – mcgrailm 2011-02-25 20:01:05

+0

我認爲你的意思是asort()(arsort是一個與索引關聯的反向排序)。 – Czechnology 2011-02-25 20:02:54

+0

@Czechnology燁,我的意思是asort。我輸入了arsort()嗎?道歉,飲料和深夜不好與良好的答案:S 感謝您編輯@Gaurav – JohnP 2011-02-25 20:06:15

2

如果需要mainatin指數的關聯,使用asort(array &$array [, int $sort_flags = SORT_REGULAR])。請注意$ array上的引用傳遞( - >檢查手冊是什麼函數輸出)。

$foo = array(
    2 => "Sports", 
    40 => "Parent and Families", 
    43 => "Arts and Entertainment", 
); 
asort($foo); 
print_r($foo); 

打印

Array 
(
    [43] => Arts and Entertainment 
    [40] => Parent and Families 
    [2] => Sports 
)