如何按某个键对多维数组进行排序? [英] How to sort a multidimensional array by a certain key?

查看:40
本文介绍了如何按某个键对多维数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单,但是如何进行呢.我想按一个键对多维数组进行排序,如下所示:

This should be really simple, but what is the way to go on this. I want to sort an multidimensional array by a key, like this:

Array (
[0] => Array
    (
        [iid] => 1
        [invitee] => 174
        [nid] => 324343
        [showtime] => 2010-05-09 15:15:00
        [location] => 13
        [status] => 1
        [created] => 2010-05-09 15:05:00
        [updated] => 2010-05-09 16:24:00
    )

[1] => Array
    (
        [iid] => 1
        [invitee] => 220
        [nid] => 21232
        [showtime] => 2010-05-09 15:15:00
        [location] => 12
        [status] => 0
        [created] => 2010-05-10 18:11:00
        [updated] => 2010-05-10 18:11:00
    ))

假设我想按 [status] 排序,我将如何实现?提前致谢!

Say i want to sort this by [status], how would I achieve this? Thanks in advance!

推荐答案

//define a comparison function
function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}

usort($array, "cmp");

这应该做你想做的,你可以改变比较函数来排序你想要的任何键.

That should do what you want, you can alter the comparison function to sort on whatever key you want.

这篇关于如何按某个键对多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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