2013-02-24 110 views
-1

我有一堆鍵的數組。我想按其值來排序其中一個鍵。如何通過PHP中的鍵對數組進行排序?

Array ( 
    [0] => stdClass Object ( 
          [id] => 1 
          [question] => Action 
          [specific_to_movie_id] => 1 
          [total_yes] => 4) 
    [1] => stdClass Object ( 
          [id] => 2 
          [question] => Created by DC Comics 
          [specific_to_movie_id] => 1 
          [total_yes] => 1) 
    [2] => stdClass Object ( 
          [id] => 3 
          [question] => Christian Bale 
          [specific_to_movie_id] => 1 
          [total_yes] => 1) 
    ) 

的陣列看起來像上面的,我想通過「Total_yes」進行排序

我怎麼能去在PHP這樣做呢?

+2

格式的輸出更好,也許有人會幫。 – Rob 2013-02-24 10:25:35

+0

無論如何,人們幫助,謝謝 – 2013-02-24 10:27:39

回答

2

你可以使用usort,如:

function cmp($a, $b) { 
    return $a < $b; 
} 

usort($your_array, "cmp"); 
3

因爲它比標準的數組排序稍微複雜一些,你需要使用usort

function compare_items($a, $b) { 
    return $a->total_yes < $b->total_yes; 
} 


$arrayToSort = array ( 
    (object) array( 
     'id' => 1, 
     'question' => 'Action', 
     'specific_to_movie_id' => 1, 
     'total_yes' => 4 
    ), 
    (object) array( 
     'id' => 2, 
     'question' => 'Created by DC Comics', 
     'specific_to_movie_id' => 1, 
     'total_yes' => 1 
    ), 
    (object) array( 
     'id' => 3, 
     'question' => 'Christian Bale', 
     'specific_to_movie_id' => 1, 
     'total_yes' => 1 
    ) 
); 


usort($arrayToSort, "compare_items"); 

如果你想扭轉排序順序,只需更改return $a->total_yes < $b->total_yes即可使用>(大於)代替<(小於)

+1

謝謝編輯@尼古拉斯皮克林:) – adomnom 2013-02-24 10:34:38

+0

我沒有太多的運氣,我實現了該功能,然後調用usort:/ – 2013-02-24 10:37:42

0

您擁有物品CT,所以你需要使用[usort()] [http://www.php.net/manual/en/function.usort.php]

​​
+0

這工作,除了它是在相反的順序比我需要的。有什麼建議麼?謝謝 ! – 2013-02-24 10:38:45

+0

@DanielFein對不起,我編輯了我的答案,現在好了 – Winston 2013-02-24 10:42:23

0

您可以使用Usort()使用特定主持人功能:

定義和用法

的usort()函數對使用用戶定義的比較 函數數組。

語法

usort(數組,myfunction的);

array -Required。指定要排序的陣列

myfunction-Optional。定義可調用比較函數的字符串。比較函數必須返回一個整數<,=,或>大於0,如果第一個參數是<,=,或>比第二個參數

<?php 

    function cmp($a, $b) 
    { 
     if ($a->total_yes == $b->total_yes) { 
      return 0; 
     } 
     return ($a->total_yes < $b->total_yes) ? -1 : 1; 
    } 



    usort($array, "cmp"); 

    ?> 
相關問題