处理排序后的数据总是更容易提取特定信息,否则你必须逐个遍历数组的每个元素。
例如,假设你将不同学生的成绩存储在一个数组或表中。如果数据没有按获得的成绩排序,则必须查看班上每个学生的成绩才能确定谁获得最高分和最低分。如果表格已经按成绩从低到高排序,只需查看第一位学生的成绩就能知道最低分。
本文将介绍以下PHP数组排序方法:
按值排序数组
排序关联数组
使用用户自定义函数按值排序数组元素
按键排序数组
排序PHP多维数组
使用用户自定义函数排序
多列排序
排序使许多需要访问或获取特定数据集的任务变得非常容易和高效。在本教程中,我们将学习如何使用内置的PHP函数来排序不同类型的数组。
在PHP中,按元素值排序数组非常容易。你可以选择保留或丢弃键值关联,也可以定义你自己的函数来决定如何排序元素。我将在本教程的这一部分向你展示如何操作。
你可以使用array_multisort()
函数,它可以根据多列或多维的值来排序多维数组。你只需要创建一个包含你想要用于排序的键值的数组。之后,只需传递排序标志即可。
下面的例子应该可以让你清楚地了解:
$players = [ [ 'name' => 'Adam', 'score' => 70, 'health' => 80 ], [ 'name' => 'Joey', 'score' => 60, 'health' => 90 ], [ 'name' => 'Monty', 'score' => 70, 'health' => 45 ], [ 'name' => 'Andrew', 'score' => 90, 'health' => 80 ], [ 'name' => 'Sally', 'score' => 60, 'health' => 85 ], [ 'name' => 'Amanda', 'score' => 98, 'health' => 50 ], [ 'name' => 'James', 'score' => 50, 'health' => 50 ] ]; $p_score = array_column($players, 'score'); $p_health = array_column($players, 'health'); array_multisort($p_score, SORT_DESC, $p_health, SORT_ASC, $players);
我们有一个多维数组,它存储玩家的姓名、分数和生命值。我们使用$p_score
和array_multisort()
函数。这将对最终结果产生影响。我们传递的$p_score
将按降序排序。这将把Amanda放在顶部,因为她的分数最高。现在,$players
数组中的元素也将重新排列,以便Amanda的生命值在$players
中位于顶部。
换句话说,$p_score
数组按降序排列。然后其他数组中的值也将重新排列以匹配该顺序。因此,顺序将是Amanda、Andrew、Adam、Monty等等。
一旦它遍历了整个$p_health
数组。你会注意到Adam和Monty的分数相同。因此,他们的最终位置将由他们的生命值决定,生命值必须按升序排序。Monty的生命值低于Adam,因此他将排在Adam之前。玩家的顺序现在将变为Amanda、Andrew、Monty、Adam等等。
所有其他值的冲突都以类似的方式解决。以下是排序数组后将获得的最终结果:
$players = [ [ 'name' => 'Adam', 'score' => 70, 'health' => 80 ], [ 'name' => 'Joey', 'score' => 60, 'health' => 90 ], [ 'name' => 'Monty', 'score' => 70, 'health' => 45 ], [ 'name' => 'Andrew', 'score' => 90, 'health' => 80 ], [ 'name' => 'Sally', 'score' => 60, 'health' => 85 ], [ 'name' => 'Amanda', 'score' => 98, 'health' => 50 ], [ 'name' => 'James', 'score' => 50, 'health' => 50 ] ]; $p_score = array_column($players, 'score'); $p_health = array_column($players, 'health'); array_multisort($p_score, SORT_DESC, $p_health, SORT_ASC, $players);
现在可能已经很明显了,但我仍然想指出sort()
调用的是单独的数组。这是一个例子:
print_r($players); /* Array ( [0] => Array ( [name] => Amanda [score] => 98 [health] => 50 ) [1] => Array ( [name] => Andrew [score] => 90 [health] => 80 ) [2] => Array ( [name] => Monty [score] => 70 [health] => 45 ) [3] => Array ( [name] => Adam [score] => 70 [health] => 80 ) [4] => Array ( [name] => Sally [score] => 60 [health] => 85 ) [5] => Array ( [name] => Joey [score] => 60 [health] => 90 ) [6] => Array ( [name] => James [score] => 50 [health] => 50 ) ) */
如果你的目的是分别按升序对这两个数组进行排序,那么就分别对这两个数组使用sort()
。
在本教程中,我向你展示了PHP中一些不同的函数,这些函数可以用来按键或值对数组进行排序。我们还学习了如何使用我们自己的自定义排序标准以及uksort()
和uasort()
函数来按键或值对数组进行排序。最后一部分讨论了如何仅使用特定字段对多维数组中的所有值进行排序。
我希望你从本教程中学到了一些新东西。如果你有任何问题或建议,请在评论中告诉我。学习的最佳方法是尝试创建你自己的例子,使用这些函数对数组进行排序。
此文章已更新,并包含Monty Shokeen的贡献。Monty是一位全栈开发人员,他也喜欢撰写教程和学习新的JavaScript库。
以上是如何在PHP中排序数组的详细内容。更多信息请关注PHP中文网其他相关文章!