2012-11-23 67 views
1

我有問題,排序此陣:由REGISTRATION_DATE我usort代碼都不盡如人意

$unsorted_users 

我想訂這種陣列DESC

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 
     ) 

) 

它存儲在變量所以它看起來像這樣:

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

你不能減去(那)字符串。如果要比較兩個字符串,這樣使用的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

+0

我得到這個錯誤:致命錯誤:無法使用類型stdClass的對象作爲數組 – Derfder

+3

是,正如@jereon所說,需要登陸 –

+0

好的,解決了,謝謝你們。 – Derfder

3

usort正在通過引用處理數組,並返回成功布爾值 - 因此您的$sorted_users包含該布爾值。現在應該對原始數組進行排序。

3

目前已經有一些有效的答案,但要加給他們:

你的變量包含在一個對象中,而不是一個數組;你必須要排序的對象數組,所以你應該使用:的

$a->registration_date 
// etc. 

代替:

$a['registration_date'] 
+2

好趕上,我們中的一些人應該拼湊一個獨特的anwser! –

+1

謝謝,現在,結合路易斯工作,謝謝;) – Derfder