I am trying to sort an array based on a particular key value in a multidimensional array as follows
我试图根据多维数组中的特定键值对数组进行排序,如下所示
<?php
$country = array(
array(
'country' => 'India',
'visits' => 22,
'newVisits' => 16,
'newVisitsPercent' => 72.7),
array(
'country' => 'USA',
'visits' => 30,
'newVisits' => 15,
'newVisitsPercent' => 50),
array(
'country' => 'Japan',
'visits' => 25,
'newVisits' => 15,
'newVisitsPercent' => 60));
?>
I wanna Sort the array in Descending order of the 'visits' key of the array.
我想按照数组的“访问”键的降序对数组进行排序。
Desired Array is
期望的阵列是
<?php
$country = array(
array(
'country' => 'USA',
'visits' => 30,
'newVisits' => 15,
'newVisitsPercent' => 50),
array(
'country' => 'Japan',
'visits' => 25,
'newVisits' => 15,
'newVisitsPercent' => 60),
array(
'country' => 'India',
'visits' => 22,
'newVisits' => 16,
'newVisitsPercent' => 72.7));
?>
Tried to search in SO all results were sorting based on the value of the key. Please let me know which function do we need to use.
试图在SO中搜索所有结果都是根据键的值进行排序。请告诉我们我们需要使用哪种功能。
I looked in to ksort, Multi-sort functions
我查看了ksort,多重排序函数
2 个解决方案
#1
4
take a look at the documentation of usort
: http://www.php.net/manual/en/function.usort.php
看一下usort的文档:http://www.php.net/manual/en/function.usort.php
#2
4
PHP has a builtin function called usort() which can sort these types of arrays.
PHP有一个名为usort()的内置函数,可以对这些类型的数组进行排序。
Your comparison function could look something like this:
您的比较函数可能如下所示:
function mycmp($a, $b) {
return intval($a['visits']) - intval($b['visits']);
}
#1
4
take a look at the documentation of usort
: http://www.php.net/manual/en/function.usort.php
看一下usort的文档:http://www.php.net/manual/en/function.usort.php
#2
4
PHP has a builtin function called usort() which can sort these types of arrays.
PHP有一个名为usort()的内置函数,可以对这些类型的数组进行排序。
Your comparison function could look something like this:
您的比较函数可能如下所示:
function mycmp($a, $b) {
return intval($a['visits']) - intval($b['visits']);
}