自然排序在array_multisort [英] array_multisort with natural sort

查看:115
本文介绍了自然排序在array_multisort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在PHP中使用自然排序进行排序多个列的多个维数组?下面是一个例子。假设我有数据的二维数组,如,

Is it possible to sort multiple dimensional array by multiple columns using natural sort in PHP? Here is an example. Suppose I have a 2D array of data, e.g.,

$array[1]['Name'] = 'John';
$array[1]['Age'] = '20';
$array[1]['Code'] = 'ABC 12';

$array[2]['Name'] = 'John';
$array[2]['Age'] = '21';
$array[2]['Code'] = 'ABC 1';

$array[3]['Name'] = 'Mary';
$array[3]['Age'] = '20';
$array[3]['Code'] = 'ABC 10';

我想这个排序数组的名字(ASC),然后按年龄(DESC),以及由code(ASC),一切都将自然排序。基本上将与自然排序进行在array_multisort。

I want to sort this array by name (ASC), then by age (DESC), and by code (ASC), all will be sorted naturally. Basically that will be array_multisort with natural sort.

我发现对网络上的这个话题很多解决方案。不幸的是,他们只用一列支持排序,而不是多列。

I found many solutions about this topic on the web. Unfortunately, they only support sorting by one column, not multiple column.

推荐答案

我认为你必须实施此行为的自定义比较函数:

I think you have to implement a custom comparison function for this behavior:

function myCmp($a, $b) {
 $nameCmp = strnatcasecmp($a['Name'], $b['Name']);
 $ageCmp = strnatcasecmp($a['Age'], $b['Age']);
 $codeCmp = strnatcasecmp($a['Code'], $b['Code']);

 if ($nameCmp != 0) // Names are not equal
   return($nameCmp);

 // Names are equal, let's compare age

 if ($ageCmp != 0) // Age is not equal
   return($ageCmp * -1); // Invert it since you want DESC

 // Ages are equal, we don't need to compare code, just return the comparison result
   return($codeCmp);
}

然后就可以调用 usort($数组,'myCmp'); 和应该得到所需的排序

这篇关于自然排序在array_multisort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆