简体   繁体   English

使用PHP对多维数组进行排序

[英]Sorting a multidimentional array using PHP

I am looking for the best way to sort a multidimensional array, I want it sorted based on what the child array contains. 我正在寻找对多维数组进行排序的最佳方法,我希望根据子数组包含的内容对其进行排序。

This is my array: 这是我的数组:

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
        )

)

And I would like to sort the 3 main arrays based on the ActionAt from their child arrays, how is this possible? 我想从子数组中基于ActionAt对3个主数组进行排序,这怎么可能?

I've read a bit about it and some say ksort and usort, but I have not been able to get it working properly. 我已经读了一些,有人说了ksort和usort,但是我无法使其正常工作。

You will need to implement your own comparison function and use usort: 您将需要实现自己的比较功能并使用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");

If you want to use usort, you'll have to make a comparison function. 如果要使用usort,则必须进行比较。 Like so: 像这样:

function mySort($a, $b)
{
    $dateA = new DateTime($a['actionAt']);
    $dateB = new DateTime($b['actionAt']);

    if($dateA < $dateB)
        return -1;
    elseif($dateA == $dateB)
        return 0;
    else
        return 1;
}

usort($myArray, "mySort");
function custom_sort($a,$b) {
    return strtolower($a['id']) > strtolower($b['id']);
}
usort($yourArray, 'custom_sort');

Note: you can change $a[] and $b[] to sort on the key you want. 注意:您可以更改$ a []和$ b []以对所需的键进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM