0

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

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Both functions work but I have gone for this as it tests if they are equal. I am not sure if Tim's answer accounts for this, but I understand this function more easily. Thanks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.