自然排序多维数组
我有一个像这样的多维数组:
array ([0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22)
[2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3))
我需要对内部数组进行排序,以便数据按 days 键按自然顺序返回。
IE 是这样的:
array ([2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3)
[0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22))
我认为我需要的是一个通过 $key 将 natsort 应用于多维数组的函数,但到目前为止我还没有找到任何除了标准排序之外的函数。
有什么帮助吗?
I have an multidimensional array like this:
array ([0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22)
[2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3))
I need to sort the inner arrays so that the data is returned in natural order by the days key.
I.E like this:
array ([2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3)
[0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22))
I think what I need is a function that applies natsort to a multidimensional array by $key, but so far I haven't been able to find any functions that do anything other than standard sorting.
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要的是 usort。
您可以编写一个回调来为您进行比较:
免责声明:您需要 PHP 5.3.x 才能正常工作,否则您必须求助于 create_function 或预定义比较函数。
What you want is usort.
You can write a callback to do the comparison for you:
Disclaimer: You need PHP 5.3.x for this to work, else you have to resort to create_function or predefine the compare function.
以下对我有用,
从这里找到:- https://learntech.imsu.ox.ac.uk/blog/php-naturally-sorting-multidimension-arrays-by-string-values/
希望有人会发现这很有用。
The following worked for me,
Found from here :- https://learntech.imsu.ox.ac.uk/blog/php-naturally-sorting-multidimension-arrays-by-string-values/
Hope someone will find this useful.
有点不同的方法:
结果:
A bit of a different approach:
Result: