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

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

问题描述

这应该是很简单的,但什么是走在这条路上。
我想通过一键进行排序的多维数组,像这样的:

 阵列(
[0] =>排列
    (
        [IID] => 1
        [受邀者] => 174
        [NID] => 324343
        [欣欣] => 2010-05-09 15:15:0​​0
        [位置] => 13
        [现状] => 1
        [创建] => 2010-05-09 15:05:00
        [更新] => 2010-05-09 16时24分○○秒
    )[1] =>排列
    (
        [IID] => 1
        [受邀者] => 220
        [NID] => 21232
        [欣欣] => 2010-05-09 15:15:0​​0
        [位置] => 12
        [现状] => 0
        [创建] => 2010-05-10 18时11分00秒
        [更新] => 2010-05-10 18时11分00秒
    ))

说我想[状态]排序这一点,我将如何实现这一目标?
在此先感谢!


解决方案

  //定义一个比较函数
功能CMP($ A,$ B){
    如果($ A ['状态'] == $ B ['状态']){
        返回0;
    }
    返回($ A ['状态'< $ B ['状态'])? -1:1;
}usort($阵列,CMP);

这是应该做你想要什么,你可以改变比较函数来排序任何你想要的关键。

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

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天全站免登陆