如何通过PHP中的键对数组进行排序?

时间:2013-02-24 10:22:54

标签: php arrays sorting

我有一堆带有一串钥匙的数组。我想按其值排序其中一个键。

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中执行此操作?

4 个答案:

答案 0 :(得分: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更改为使用&gt; (大于)代替&lt; (小于)

答案 1 :(得分:2)

您可以使用usort,例如:

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

usort($your_array, "cmp");

答案 2 :(得分:0)

你有对象,因此你需要使用[usort()] [http://www.php.net/manual/en/function.usort.php]

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

答案 3 :(得分:0)

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

定义和用法

  

usort()函数使用用户定义的比较对数组进行排序   功能

<强>语法

  

usort(数组,myfunction的);

数组 - 需要。指定要排序的数组

<强> myfunction的-可选即可。用于定义可调用比较函数的字符串。比较函数必须返回一个整数&lt;,=或&gt;如果第一个参数是&lt;,=,或者>比第二个论点

<?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");

    ?>