PHP usort重新排序数组,所有的排序值都相同 [英] PHP usort reorders array the sort value is the same for all
问题描述
我正在使用usort对每个元素中具有关联数组的数组进行排序.
I'm using usort to sort an array with an associative array within each element.
当我在数组中排序的所有值都相同时,它仍然会更改数组中元素的位置,是否有办法防止这种情况发生?
When all of the values I am sorting on in the array are the same then it still changes the position of the elements in the array, is there a way to prevent this?
例如:
array(
array('name' => 'Ben', 'authn_weight' => 85.3),
array('name' => 'Josh', 'authn_weight' => 85.3),
array('name' => 'Fred', 'authn_weight' => 85.3)
);
可以更改为此:
array(
array('name' => 'Josh', 'authn_weight' => 85.3),
array('name' => 'Ben', 'authn_weight' => 85.3),
array('name' => 'Fred', 'authn_weight' => 85.3)
);
这是排序功能:
private function weightSortImplementation($a, $b){
$aWeight = $a['autn_weight'];
$bWeight = $b['autn_weight'];
if ($aWeight == $bWeight) {
return 0;
}
return ($aWeight < $bWeight) ? 1 : -1;
}
我检查了weightSortImplementation
函数是否始终返回0,表明它们相同.那么为什么仍要对数组重新排序?
I have checked that the weightSortImplementation
function is always returning 0 showing that they are the same. So why is this still reordering the array?
推荐答案
啊哈,是 Schwartzian变换的案例.
它基本上包括三个步骤:
It basically consists of three steps:
-
装饰您将每个值变成一个数组,该数组的值是第一个元素,键/索引是第二个
- 排序(按照常规)
- 无法装饰;您反转步骤1
- decorate; you turn every value into an array with the value as the first element and the key/index as the second
- sort (as per normal)
- undecorate; you reverse step 1
在这里(我已将其调整为您的特定用例):
Here it is (I've tweaked it to your particular use case):
function decorate(&$v, $k)
{
$v['authn_weight'] = array($v['authn_weight'], $k);
}
function undecorate(&$v, $k)
{
$v['authn_weight'] = $v['authn_weight'][0];
}
array_walk($a, 'decorate');
usort($a, 'weightSortImplementation');
array_walk($a, 'undecorate');
诀窍在于以下断言:
array($x, 0) < array($x, 1)
这就是保持阵列正确顺序的原因.而且,无需递归:)
This is what keeps the correct order of your array. And, no recursion required :)
这篇关于PHP usort重新排序数组,所有的排序值都相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!