2012-07-17 185 views
3

我有一個複雜的多維數組。結構是這樣的php多維數組排序問題

Array 
(
    [0] => Array 
     (
      [countries] => Array 
       (
        [0] => Array 
         (
          [country_code] => US        
          [growth] => 3.57 
         ) 

        [1] => Array 
         (
          [country_code] => CA        
          [growth] => 4.77 
         ) 

        [2] => Array 
         (
          [country_code] => TT        
          [growth] => 0 
         ) 
       ) 
      [group_name] => North America 
     ) 

    [1] => Array 
     (
      [countries] => Array 
       (
        [0] => Array 
         (
          [country_code] => BR       
          [growth] => 2.19 
         ) 

        [1] => Array 
         (
          [country_code] => PE       
          [growth] => 1.78 
         ) 

        [2] => Array 
         (
          [country_code] => UY       
          [growth] => 8.83 
         ) 

        [3] => Array 
         (
          [country_code] => MX       
          [growth] => 3.83 
         ) 
       ) 
      [group_name] => South America 
     ) 
) 

我想對它們進行排序(可以是通過使用array_multisort),以便它們按照growth(由高到低)排序

使數組排序將是

Array 
(
    [0] => Array 
     (
      [countries] => Array 
       (
        [0] => Array 
         (
          [country_code] => CA        
          [growth] => 4.77 
         ) 
        [1] => Array 
         (
          [country_code] => US        
          [growth] => 3.57 
         )     
        [2] => Array 
         (
          [country_code] => TT        
          [growth] => 0 
         ) 
       ) 
      [group_name] => North America 
     ) 

    [1] => Array 
     (
      [countries] => Array 
       (
        [0] => Array 
         (
          [country_code] => UY       
          [growth] => 8.83 
         ) 

        [1] => Array 
         (
          [country_code] => MX       
          [growth] => 3.83 
         ) 
        [2] => Array 
         (
          [country_code] => BR       
          [growth] => 2.19 
         ) 

        [3] => Array 
         (
          [country_code] => PE       
          [growth] => 1.78 
         ) 
       ) 
      [group_name] => South America 
     ) 
) 

我是新來的PHP,所以我想不出如何排序這個複雜的數組。我知道如何對簡單的多維數組進行排序,如http://in2.php.net/manual/en/function.array-multisort.php

+0

什麼問題? – Lion 2012-07-17 15:00:09

+0

我想排序一個複雜的數組,我不知道該怎麼做。我已閱讀手冊,但無法爲這樣一個複雜的數組獲得一個好例子。 – 2012-07-17 15:05:59

+0

請顯示您的代碼 – 2012-07-17 15:44:44

回答

2

最糟糕的情況是,您使自己的排序功能和使用usort
它實際上是爲這些事情設計的。

對您而言,您將通過$arr[$i]['countries']並根據$arr['growth']進行比較功能排序。

0

我用我下面的排序功能好幾年了: