如何在php中降序数组中排序二维数组?

时间:2016-03-26 13:02:31

标签: php arrays sorting

我有以下数组,我想在php中的“count”索引值的基础上按降序对此数组进行排序。我使用了以下代码,但它不适用于我。请给我提示按降序排序数组。

数组: -

Array ( [0] => Array ( [text] => this is text [count] => 0 ) 
        [1] => Array ( [text] => this is second text [count] => 2 ) 
        [2] => Array ( [text] => this is third text [count] => 1 )
      )

我尝试过以下代码。

function sort_count($a, $b) {
    return $a['count'] - $b['count'];
}
$sorted_array = usort($array, 'sort_count');

4 个答案:

答案 0 :(得分:2)

升序..

usort($your_array, function($a, $b) {
   return $a['count'] - $b['count'];
});

降序..

usort($your_array, function($a, $b) {
   return $b['count'] - $a['count'];
});

Example here

答案 1 :(得分:0)

你可以使用像

这样的核心php函数
rsort ($array)
arsort($array) 

你也应该在php手册中阅读这篇文章 http://php.net/manual/en/array.sorting.php

答案 2 :(得分:0)

以下是解决方案:

$a1 = array (array ( "text" => "this is text", "count" => 0 ), 
    array ( "text" => "this is text", "count" => 1 ),
    array ( "text" => "this is text", "count" => 2 ),
  );
usort($a1 ,sortArray('count')); 
function sortArray($keyName) {
  return function ($a, $b) use ($keyName) {return ($a[$keyName]< $b[$keyName]) ? 1 : 0;
    };
}
print_r($a1);

答案 3 :(得分:0)

试试这个:

注意:检查您的平等是一个额外的好处。

function sort_count($a, $b) {
   if ($a['count'] === $b['count']) {
      return 0;
   } else {
       return ($a['count'] > $b['count'] ? 1:-1);
   }
}
$sorted_array = usort($array, 'sort_count');

echo "<pre>";

print_r($array);

echo "</pre>";

希望这有帮助。