PHP 按字段名称对多维数组进行排序
我尝试调整此代码以用于对命名键/字段上的多维数组进行排序。该字段是一个整数,我需要将其从最小到最大排序。
function myCmp($a, $b)
{
return strcmp($a["days"], $b["days"]);
}
uasort($myArray, "myCmp");
这会根据我的需要对数组进行排序,但顺序错误。目前它从最大到最小排序,不使用自然顺序。我需要按自然顺序从最小到最大排序(例如,2 在 5、12 和 24 之前)。
I have tried adapting this code to use to sort a multidimensional array on a named key/field. The field is an integer what I need to sort smallest to biggest.
function myCmp($a, $b)
{
return strcmp($a["days"], $b["days"]);
}
uasort($myArray, "myCmp");
This sorts the arrays as I need but in the wrong order. At the moment it sorts biggest to smallest, not using natural order. I need to sort smallest to biggest in natural order (eg 2 comes before 5, 12 and 24).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strnatcmp() 是你的朋友
,例如(使用 php 5.3 闭包/匿名函数):
打印
strnatcmp() is your friend
e.g. (using a php 5.3 closure/anonymous function):
prints
您可以反转 strcmp 的参数:
You can just reverse the parameters of strcmp :
由于您想按自然顺序排序,因此您不应该使用
strcmp
,您可以这样做:这是一个 工作示例。
Since you want to sort in natural order you should not be using
strcmp
, you can do:Here is a working example.