问题描述
是否可以在 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)和按代码(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($array, 'myCmp');
并且应该得到想要的排序
Then you can call usort($array, 'myCmp');
and should get the desired sorting
这篇关于array_multisort 与自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!