1

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

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 代码错误?

4

3 回答 3

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!

?>

在这里摆弄

于 2012-11-23T17:48:31.700 回答
3

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

于 2012-11-23T17:47:17.127 回答
3

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

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

$a->registration_date
// etc.

代替:

$a['registration_date']
于 2012-11-23T17:50:18.063 回答