natsort多维度数组 [英] natsort multidemsional array

查看:118
本文介绍了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))

我需要对内部数组进行排序,以便通过days键以自然顺序返回数据.

I need to sort the inner arrays so that the data is returned in natural order by the days key.

我是这样的:

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 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.

有帮助吗?

推荐答案

您想要的是 usort

您可以编写一个回调为您做比较:

You can write a callback to do the comparison for you:

usort($data, function($a, $b) {
    return ($a['days'] > $b['days'])
           ? 1 
           : ($a['days'] < $b['days'])
             ? -1 
             : 0;
});

免责声明:您需要PHP 5.3.x才能正常工作,否则必须诉诸 create_function 或预定义比较功能.

Disclaimer: You need PHP 5.3.x for this to work, else you have to resort to create_function or predefine the compare function.

这篇关于natsort多维度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆