簡體   English   中英

使用PHP對多維數組進行排序

[英]Sorting a multidimentional array using PHP

我正在尋找對多維數組進行排序的最佳方法,我希望根據子數組包含的內容對其進行排序。

這是我的數組:

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個主數組進行排序,這怎么可能?

我已經讀了一些,有人說了ksort和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");

如果要使用usort,則必須進行比較。 像這樣:

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

注意:您可以更改$ a []和$ b []以對所需的鍵進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM