PHP 的排序无法正常工作?

发布于 2024-09-18 09:10:58 字数 678 浏览 5 评论 0原文

我有一个示例数组:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

壹場煙雨 2024-09-25 09:10:58

您不能期望相同的值具有特定的排序顺序。来自 关于排序数组的 PHP 手册

如果这些排序函数中的任何一个将两个成员评估为相等,则顺序未定义(排序不稳定)。

You can't expect a certain sorting order for equal values. From the PHP manual on Sorting Arrays:

If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

誰ツ都不明白 2024-09-25 09:10:58

“为什么”是另一个问题。
但它确实满足了您的要求,不是吗?
按键顺序尚未确定。
如果你想要一定的按键顺序,你应该在练习条件中注明

"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

我们只是彼此的过ke 2024-09-25 09:10:58

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)

菩提树下叶撕阳。 2024-09-25 09:10:58

根据排序算法,它可能以另一种方式开始排序,而不仅仅是检测到它应该只移动该单个对。但最终得到了一个维护键/值的有效排序数组。它们看起来只是交换了,因为您有 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文