我应该如何解决这阵与usort键? [英] How should I sort this array by key with usort?

查看:160
本文介绍了我应该如何解决这阵与usort键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能已经阅读每 usort StackOverflow上的文章,但我不能工作了这一个。这可能是 usort 不是工具,我需要什么?下面是一个数组的一点是我的工作(我把它分配给 $所有页

I think I might have read every usort article on StackOverflow, but I can't work out this one. It might be that usort is not the tool I need? Here's a bit of the array that I'm working with (I have it assigned to $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
        )
)

我想最终排序的 created_on 价值,但就目前而言,我对能够排序其中的任何解决!当我尝试正常 CMP($ A,$ B) usort 键入回调 - ,例如,在<一个href=\"http://stackoverflow.com/questions/3072445/sorting-by-a-specific-key-of-a-multi-dimensional-array-php/3072489#3072489\">this回答一个问题usort - 我只是得到了一个空白。例如:

I am trying ultimately to sort on the created_on value, but for the moment, I'd settle on being able to sort on any of them! When I try the normal cmp($a, $b) type callback with usort -- as, for example, in this answer on a usort question -- I just get a blank. Example:

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

的print_r 给我什么。这是用PHP 5.2.n,而不是5.3 BTW。

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

指导,好吗?和Thankyou!

Guidance, please? And thankyou!

推荐答案

您数组中的项目对象,而不是关联数组,所以你需要参考他们这样的:

Your items in the array are objects, not associative arrays, so you need to refer to them like this:

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

这篇关于我应该如何解决这阵与usort键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆