How should I sort this array by key using usort?

I think I may have read every article usorton StackOverflow, but I can't work it out. Maybe usortnot the tool I need? Here is a bit of the array I'm working with (I assigned it $allPages):

Array
(
    [0] => Page Object
        (
            [id] => 4
            [slug] => articles
            [created_on] => 2009-08-06 07:16:00
        )

    [1] => Page Object
        (
            [id] => 99
            [slug] => a-brief-history
            [created_on] => 2011-04-25 12:07:26
        )

    [2] => Page Object
        (
            [id] => 98
            [slug] => we-arrive
            [created_on] => 2011-04-24 13:52:35
        )

    [3] => Page Object
        (
            [id] => 83
            [slug] => new-year
            [created_on] => 2011-01-02 14:05:12
        )
)

I end up trying to sort the value created_on, but for now, I agree to be able to sort by any of them! When I try to make a normal cmp($a, $b)type callback usort- like, for example, in this answer to a given question - I just get empty. Example:

function cmp($a, $b) {
  return strcmp($a["slug"], $b["slug"]);
}
usort($allPages, 'cmp')

And print_rit gives nothing. This is with PHP 5.2.n, not 5.3 btw.

Guide please? And thanks!

+5
3

, , :

function cmp($a, $b) {
  return strcmp($a->slug, $b->slug);
}
usort($allPages, 'cmp')
+4

, - , . , $a->created_on $a['created_on']? .

...

+3

@Tesserex, .

, .

Another thing to keep in mind is that not all of your pages have a created_on attribute, some have a published_on attribute. You will need to do some error checking / logic inside your usort method to make sure the key you want to sort is available and to do something when it is not.

+1
source

All Articles