PHP 的排序无法正常工作?
我有一个示例数组:
$a = array(
5 => 35,
16 => 22,
7 => 22,
3 => 22,
11 => 22,
9 => 27,
);
我想按值对其进行排序并记住它的键。 我期望的结果是:
$a = array(
16 => 22,
7 => 22,
3 => 22,
11 => 22,
9 => 27,
5 => 35,
);
所以我的第一个想法是:asort
! 好吧,我做到了
asort($a);
,但是不 - 它不只是移动 5 => 35
到数组末尾。 它将我的数组更改为:
$a = array(
11 => 22,
3 => 22,
7 => 22,
16 => 22,
9 => 27,
5 => 35
);
你看到了吗?具有相同值的键被反向排序。为什么 ?
I have an example array:
$a = array(
5 => 35,
16 => 22,
7 => 22,
3 => 22,
11 => 22,
9 => 27,
);
and I want to sort it by values and remember its keys.
Result that I expected was:
$a = array(
16 => 22,
7 => 22,
3 => 22,
11 => 22,
9 => 27,
5 => 35,
);
So my first thought was: asort
!
Ok, I did
asort($a);
But no - it didn't just move 5 => 35
to the end of the array.
It changed my array to:
$a = array(
11 => 22,
3 => 22,
7 => 22,
16 => 22,
9 => 27,
5 => 35
);
You see ? Keys with the same value are reverse sorted. Why ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能期望相同的值具有特定的排序顺序。来自 关于排序数组的 PHP 手册:
You can't expect a certain sorting order for equal values. From the PHP manual on Sorting Arrays:
“为什么”是另一个问题。
但它确实满足了您的要求,不是吗?
按键顺序尚未确定。
如果你想要一定的按键顺序,你应该在练习条件中注明
"Why" is another question.
But it actually did what you were asking for, didn't it?
Key order weren't determined.
If you want certain order of keys, you should state it in the exercise conditions
http://en.wikipedia.org/wiki/Sorting_algorithm#Stability
简而言之,确保已经排序的键的顺序保持不变会花费计算时间(无论谁在 PHP 中设计该函数,都认为这不值得)
http://en.wikipedia.org/wiki/Sorting_algorithm#Stability
in short, making sure that the order of the already sorted keys remains the same would cost computation time (and whoever designed the function at PHP decided it wasn't worth it)
根据排序算法,它可能以另一种方式开始排序,而不仅仅是检测到它应该只移动该单个对。但最终得到了一个维护键/值的有效排序数组。它们看起来只是交换了,因为您有 4 个值为
22
的键。Depending on the sort algorithm, it probably started sorting in another manner than just detecting that it should only move that single pair. But it ended up with a validly sorted array maintaining keys/values. they only look swapped cuz you have 4 keys with values of
22
.