排序使用PHP多维数组 [英] Sorting a multidimentional array using PHP

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

问题描述

我要寻找排序多维数组的最佳方式,我希望它基于​​什么孩子数组包含排序。

I am looking for the best way to sort a multidimensional array, I want it sorted based on what the child array contains.

这是我的数组:

Array
(
    [0] => Array
        (
            [id] => 2
            [level] => 3
            [lastAction] => "String Here" 
            [actionAt] => 23/03/2014
        )

    [1] => Array
        (
            [id] => 4
            [level] => 5
            [lastAction] => "Another String here"
            [actionAt] => 24/3/2014
        )

    [2] => Array
        (
            [id] => 9
            [level] => 1
            [lastAction] => "String again"
            [actionAt] => 01/01/2013
        )

)

和我想基础上,从ActionAt他们的孩子阵列中的3个主要数组排序,这怎么可能?

And I would like to sort the 3 main arrays based on the ActionAt from their child arrays, how is this possible?

我读过一些关于它有的说ksort和usort,但我一直没能得到它正常工作。

I've read a bit about it and some say ksort and usort, but I have not been able to get it working properly.

推荐答案

您将需要实现自己的比较函数,并使用usort:

You will need to implement your own comparison function and use usort:

function cmp($a, $b)
{
    if ($a['actionAt'] == $b['actionAt']) {
        return 0;
    }

    //Assuming your dates are strings (http://stackoverflow.com/questions/2891937/strtotime-doesnt-work-with-dd-mm-yyyy-format)
    $atime = strtotime(str_replace('/', '-', $a['actionAt']));
    $btime = strtotime(str_replace('/', '-', $b['actionAt']));

    return ($atime < $btime) ? -1 : 1;
}

usort($array, "cmp");

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

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