5

I have an array like this:

Array
(
    [0] => Array
        (
            [title] => some title
            [time] => 1279231500
        )

    [1] => Array
        (
            [title] => some title 2
            [time] => 1279231440
        )
    
    [2] => Array
        (
            [title] => some title 3
            [time] => 1279229880
        )
)

How I can sort it based on time?

0

2 Answers 2

4

You can sort it this way (since it is an associative array):

function cmp($a, $b)
{
   return strcmp($a['time'], $b['time']);
}

usort($your_array, "cmp");
print_r($your_array);
Sign up to request clarification or add additional context in comments.

4 Comments

any idea how to reverse the order?
@greenbandit - Change the comparison function to return strcmp($b['time'], $a['time']); - usort() is sorting based on cmp().
@reverse: Either return -1 * strcmp(...); or apply array_reverse after sort.
You should not use strcmp for integer values. Because 2 < 12 but strcmp(2, 12) === 1 that means “2 is greater than 12”.
1

As Gumbo mentioned, you should not use strcmp for integer values.

Use this function

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

1 Comment

For integer values, return $a['time'] - $b['time']; would suffice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.