2013-02-24 112 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"); 

    ?> 
相关问题