使用 usort 对数组进行排序?
我在尝试对数组进行排序时遇到问题 - 我希望所有 IsOpen = 1 出现在顶部?
示例:
Array
(
[0] => Array
(
[Isopen] => 0
)
[2] => Array
(
[Isopen] => 1
)
[3] => Array
(
[Isopen] => 0
)
[4] => Array
(
[Isopen] => 1
)
代码:
function cmp($a, $b) {
if ($a['Isopen'] >= $b['Isopen']) {
return 0;
}
}
usort($data['rowResult'], "cmp");
我不明白 $a 和 $b 是什么意思,我查看了 PHP 文档 - 信息不清楚。
I am having problem trying to sort an array - I want all the IsOpen = 1 to appear at the top?
Example:
Array
(
[0] => Array
(
[Isopen] => 0
)
[2] => Array
(
[Isopen] => 1
)
[3] => Array
(
[Isopen] => 0
)
[4] => Array
(
[Isopen] => 1
)
Code:
function cmp($a, $b) {
if ($a['Isopen'] >= $b['Isopen']) {
return 0;
}
}
usort($data['rowResult'], "cmp");
I don't understand what does $a and $b mean, I had a look at the PHP documentation - information is not clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
$a 和 $b 是要比较的元素:
$a and $b are the elements to compare:
cmp 函数应返回 0、-1(或小于零)或 1(或大于零)。
为了比较两个值,您可以使用 php 函数 strcmp
The cmp funciton should return 0, -1 (or less than zero) or 1 (or greater than zero).
for the comparison of the two values you may use php function strcmp
这将使 Isopen = 1 在数组的末尾,如果你想在乞求它
this will makes Isopen = 1 at the end of the array if you want it at the begging make this
在此示例中,$a[] 和 $b[] 是传递给名为“cmp”的函数的两个数组。它比较两个不同数组中“Isopen”的值。
查看有关用户定义函数的文档
http://php.net/manual/en/language.functions.php
以及如何正确使用 usort()
http://php.net/manual/en/function.usort.php
in this example $a[] and $b[] are two arrays that are handed to the function named 'cmp'. it compares the value of 'Isopen' in two different arrays.
check out the documentation on user defined functions
http://php.net/manual/en/language.functions.php
and how to properly use usort()
http://php.net/manual/en/function.usort.php
排序算法是冒泡排序。
本质上,它一次比较数组实体以确定它们的顺序。要查看分步示例,请参阅 http://en.wikipedia.org/ wiki/Bubble_sort#Step-bystep_example
The sorting aglorithm is a Bubble Sort.
Essentially, it compares array entities at a time to determining their ordering. To see a step by step example, see http://en.wikipedia.org/wiki/Bubble_sort#Step-by-step_example
您的函数 cmp 不正确(请参阅我的正确使用示例)。此外,如果你使用 php 5.3+,你可以使用这样的匿名函数:
Your function cmp is not correct (see my example of correct use). Besides if you use php 5.3+ you can use anonymous functions like this: