开发者

How to sort a multi-dimensional array by values which are dates?

开发者 https://www.devze.com 2023-02-12 12:29 出处:网络
I am struggling with this. Sorting a multi-dimensional array by value based on dates. Here is a snippet of the array:

I am struggling with this. Sorting a multi-dimensional array by value based on dates. Here is a snippet of the array:

Array
(
    [0] => Array
        (
            [clicks] => 14
            [point] => 11 February 2011
        )

    [1] => Array
        (
            [clicks] => 1
            [point] => 14 February 2011
        )

    [2] => Array
        (
            [clicks] => 8
            [point] => 15 February 2011
        )

    [3] => Array
        (
            [clicks] => 0
            [point] => 08 February 2011
        )

I would like to sort it by date with the keys in the correct order. So in开发者_StackOverflow社区 this case the 08 February 2011 should get key 0. I tried to make use of usort but that didn't go well as I couldn't even make use of the callback function in codeigniter which is another problem I am researching.

What is the most efficient way of doing this? My array can grow to 60 entries.

Thanks all for any help.


This custom sort should work:

function cmp($a, $b){
    $l = strtotime($a['point']);
    $r = strtotime($b['point']);
    if($l == $r){
        return 0;
    }
    return $l < $r ? -1 : 1;
}

usort($arr, "cmp");


Suppose, $data is your multi-dimensional array.

foreach ($data as $key => $row) {
    $point[$key]  = strtotime($row['point']);
}

// Sort the data with date ascending
array_multisort($point, SORT_ASC, $data);

See array_multisort function: http://php.net/manual/en/function.array-multisort.php (very useful for sorting multi-dimensional arrays)

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消