2016-03-26 35 views
-1

我有以下数组,我想在php中的“count”索引值的基础上以降序对这个数组进行排序。我已经使用了下面的代码,但它不适合我。请给我提示按降序对数组进行排序。如何排序在php中降序数组中的二维数组?

阵列: -

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'); 
+2

它已经有一个解决方案在这里:http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value –

回答

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

希望这会有所帮助。

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

+0

这将工作在PHP 5.3或更高。 (匿名功能)如果您的版本较低。您需要先定义函数。就像你在你的例子中做的那样。 – KyleK

+0

它不按降序排列 – RomanPerekhrest

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