2012-05-02 63 views
1

在CakePHP中查找語句產生如下結構的數組。 我已經訂購了我的搜索以生成顯示的結果集(按combined_score排序)。現在,我想對數據應用排序功能,按「average_votes」進行排序。請參閱下面的「從此:」/「到此:」。如何對CakePHP多維數組進行排序?

我真的很感激任何建議。

From this: 
Array 
(
[0] => Array 
    (
     [Vehicle] => Array 
      (
       [id] => 52 
       [user_id] => 101 
       [name] => Ford 
       [total_votes] => 5 
       [average_votes] => 3.8 
       [combined_score] => 19 
      ) 

    ) 

[1] => Array 
    (
     [Vehicle] => Array 
      (
       [id] => 48 
       [user_id] => 101 
       [name] => Nissan 
       [total_votes] => 6 
       [average_votes] => 5 
       [combined_score] => 2 
      ) 
    ) 
) 

To this: 
Array 
(
[0] => Array 
    (
     [Vehicle] => Array 
      (
       [id] => 48 
       [user_id] => 101 
       [name] => Nissan 
       [total_votes] => 6 
       [average_votes] => 5 
       [combined_score] => 2 
      ) 
    ) 

[1] => Array 
    (
     [Vehicle] => Array 
      (
       [id] => 52 
       [user_id] => 101 
       [name] => Ford 
       [total_votes] => 5 
       [average_votes] => 3.8 
       [combined_score] => 19 
      ) 

    ) 

) 
+0

請看「相關」部分在右邊。 – Jon

+2

爲什麼你沒有數據庫做排序? – ori

+0

喬恩,這些相關鏈接中的哪一個顯示如何按上面所示的3級深度數據進行排序? – stevenmc

回答

2

取決於你實際上要達到你仍然可以做到這一點在蛋糕數據庫級別,像這樣:

$this->Vehicle->find('all',array('order' => array('Vehicle.combined_score' => 'asc', 'Vehicle.average_votes' => 'desc'))); 

哪個會先排序按組合的匹配度,然後按平均票

第二個選擇是使用CakePHP的Set類,像這樣:

$results = Set::sort($results, '{n}.Vehicle.average_votes', 'desc'); 
2

在你的控制器的查找功能,你可以添加選項進行排序。

$this->Vehicle->find('all',array('order' => array('Vehicle.average_votes DESC'))); 
+0

感謝gvLearner,但正如我在我的文章中提到的,我首先需要按照combined_score排序,然後我需要採用該結果集並按平均投票結果。 – stevenmc

相關問題