php 数组的稳定排序可通过以下方法实现:创建一个自定义比较器,比较时考虑原始索引;使用 uasort() 函数,根据键对值排序,并将值设置为包含原始索引的元素;这些方法确保相等元素在排序后的顺序与原始顺序相同。

PHP 数组稳定排序:保持相等元素的顺序
简介
稳排序确保相等元素在排序后的顺序与原始顺序相同。对于稳定排序,以下比较是有效的:
a == b => sort(a) <p>PHP 数组原生的 <code>sort()</code> 和 <code>rsort()</code> 函数是不稳定的。本篇文章将探究稳定排序的方法。</p><p><strong>方法</strong></p><p><strong>1. 自定义比较器</strong></p><p>使用自定义比较器,在相等元素时比较它们的原始索引:</p><pre class="brush:php;toolbar:false;">function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return $a <p>然后在 <code>usort()</code> 或 <code>uksort()</code> 函数中使用它:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build MCP servers and clients for PHP applications with the official PHP SDK" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="overflowclass">Build MCP servers and clients for PHP applications with the official PHP SDK</a>
<p class="overflowclass">使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><pre class="brush:php;toolbar:false;">usort($arr, 'cmp');
2. 使用 uasort()
uasort() 根据键对值进行排序,ksort() 对键进行排序。因此,您可以将数组中的值设置为一个包含原始索引的元素,然后对键进行排序:
$indices = array_keys($arr);
uasort($arr, function($a, $b) use ($indices) {
if ($a == $b) {
return 0;
}
return $indices[array_search($a, $arr)] <p><strong>实战案例</strong></p><p>对学生成绩数组按分数进行排序,同时保持同分学生原始的顺序:</p><pre class="brush:php;toolbar:false;">$scores = [
'John' => 90,
'Mary' => 85,
'Bob' => 85,
'Alice' => 95
];
uasort($scores, function($a, $b) {
if ($a == $b) {
return 0;
}
return $a <p>输出:</p><pre class="brush:php;toolbar:false;">Array
(
[Alice] => 95
[John] => 90
[Bob] => 85
[Mary] => 85
)
结论
上面列出的方法可以实现 PHP 数组的稳定排序,以便保持相等元素的顺序。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










