我的usort代码运行不正常

时间:2012-11-23 17:42:05

标签: php

我对排序这个数组有问题:

Array
(
    [0] => stdClass Object
        (
            [id] => 120
            [registration_date] => 2012-10-19 16:57:46
            [username] => Jeff
        )
    [1] => stdClass Object
        (
            [id] => 121
            [registration_date] => 2012-12-23 16:57:46
            [username] => Peter
        )
    [2] => stdClass Object
        (
            [id] => 122
            [registration_date] => 2012-11-30 16:57:46
            [username] => Susan
        )

)

它存储在变量:

$unsorted_users

我想通过 registration_date 订购此数组 DESC ,所以看起来像这样:

Array
    (
        [0] => stdClass Object
            (
                [id] => 121
                [registration_date] => 2012-12-23 16:57:46
                [username] => Peter

            )
        [1] => stdClass Object
            (
                [id] => 122
                [registration_date] => 2012-11-30 16:57:46
                [username] => Susan

            )
        [2] => stdClass Object
            (
                [id] => 120
                [registration_date] => 2012-10-19 16:57:46
                [username] => Jeff
            )

    )

,它按registration_date排序,如:

2012-12-23 16:57:46
2012-11-30 16:57:46
2012-10-19 16:57:46

而不是原来的地方:

2012-10-19 16:57:46
2012-12-23 16:57:46
2012-11-30 16:57:46

我正在使用此代码,但它运行不正常(print_r($ sorted_users); $ sorted_users的输出为“1”。我不知道为什么它是1而不是排序数组。)

$sorted_users = usort($unsorted_users, function($a, $b) {
   return $a['registration_date'] - $b['registration_date'];
});

任何建议为什么我的$ sorted_users代码错了?

3 个答案:

答案 0 :(得分:4)

你不能减去(那)字符串。如果要比较两个字符串,请使用strcmp()函数,如下所示:

<?php

//  setup
$unsorted_users = array();

$t = new stdClass(); 
$t->id = 120; $t->username = 'jeff'; $t->registration_date = '2012-10-19 16:57:46'; 
$unsorted_users[] = $t;

$t = new stdClass(); 
$t->id = 121; $t->username = 'Peter'; $t->registration_date = '2012-12-23 16:57:46'; 
$unsorted_users[] = $t;

$t = new stdClass(); 
$t->id = 122; $t->username = 'Susan'; $t->registration_date = '2012-11-30 16:57:46'; 
$unsorted_users[] = $t;
// end setup


$sorted_users =    // this var is nor relevant as it shoud be allways true
usort($unsorted_users, function($a, $b) {
   return strcmp ($a->registration_date, $b->registration_date) ;
});

echo '<pre>';
print_r($unsorted_users)   // that is in fact ordered!

?>

小提琴here

答案 1 :(得分:3)

usort正在通过引用处理数组,并返回成功boolean - 所以你的$sorted_users包含该布尔值。现在应该对原始数组进行排序。

答案 2 :(得分:3)

已经有一些有效的答案,但要添加它们:

您的变量包含在对象中,而不是数组中;你有一个你想要排序的对象数组,所以你应该使用:

$a->registration_date
// etc.

而不是:

$a['registration_date']