如何通过某些特定键对数组进行排序?

时间:2021-11-03 21:32:38

I have an array look like below.

我有一个如下所示的数组。

$array[0]['keyword']  = 'cricket ';
$array[0]['noofhits'] = '26';

$array[1]['keyword']  = 'food  ';
$array[1]['noofhits'] = '17';

$array[2]['keyword']  = 'mypax';
$array[2]['noofhits'] = '22';

$array[3]['keyword']  = 'next';
$array[3]['noofhits'] = '22';

$array[4]['keyword']  = 'nextbutton';
$array[4]['noofhits'] = '22';

$array[5]['keyword']  = 'picture';
$array[5]['noofhits'] = '18';

I want to sort the array using the noofhits. How can I do? Advance Thanks for your advice.

我想使用noofhits对数组进行排序。我能怎么做?预先感谢您的建议。

Soory for the previous one.Thanks for your answers.

上一个的索里。谢谢你的答案。

1 个解决方案

#1


9  

Use usort with a custom comparison function:

使用带有自定义比较功能的usort:

function cmp($a, $b) {
    return $a['noofhits'] - $b['noofhits'];
}
usort($array, 'cmp');

usort expects the comparison function to return three different value:

usort期望比较函数返回三个不同的值:

  • 0 if a and b are equal
  • 如果a和b相等,则为0
  • integer less than 0 if a precedes b
  • 如果a先于b,则小于0的整数
  • integer greater than 0 if b precedes a
  • 如果b在a之前,则整数大于0

So we can simply subtract the value of b from a. If a’s value is greater than b’s value, the subtraction yields a positive integer; if a’s value is equal to b’s value, it yields 0; and if a’s value is less than b’s value, it yields a negative value.

所以我们可以简单地从a中减去b的值。如果a的值大于b的值,则减法产生正整数;如果a的值等于b的值,则得到0;如果a的值小于b的值,则产生负值。

#1


9  

Use usort with a custom comparison function:

使用带有自定义比较功能的usort:

function cmp($a, $b) {
    return $a['noofhits'] - $b['noofhits'];
}
usort($array, 'cmp');

usort expects the comparison function to return three different value:

usort期望比较函数返回三个不同的值:

  • 0 if a and b are equal
  • 如果a和b相等,则为0
  • integer less than 0 if a precedes b
  • 如果a先于b,则小于0的整数
  • integer greater than 0 if b precedes a
  • 如果b在a之前,则整数大于0

So we can simply subtract the value of b from a. If a’s value is greater than b’s value, the subtraction yields a positive integer; if a’s value is equal to b’s value, it yields 0; and if a’s value is less than b’s value, it yields a negative value.

所以我们可以简单地从a中减去b的值。如果a的值大于b的值,则减法产生正整数;如果a的值等于b的值,则得到0;如果a的值小于b的值,则产生负值。