2010-11-22 59 views
4

如何通過任何子值(即:post_id,用戶名等)對以下數組排序?按子值排序父數組

Array(
[0] => Array 
    (
     [id] => 10 
     [post_id] => 398 
     [user_id] => 0 
     [view_date] => 2010-11-20 15:26:00 
     [views] => 4 
     [username] => <em>guest</em> 
    ) 

[1] => Array 
    (
     [id] => 9 
     [post_id] => 397 
     [user_id] => 1 
     [view_date] => 2010-11-19 23:35:39 
     [views] => 1 
     [username] => Fire G 
    ) 

[2] => Array 
    (
     [id] => 8 
     [post_id] => 398 
     [user_id] => 1 
     [view_date] => 2010-11-19 23:35:26 
     [views] => 4 
     [username] => Fire G 
    ) 

[3] => Array 
    (
     [id] => 7 
     [post_id] => 396 
     [user_id] => 1 
     [view_date] => 2010-11-19 23:07:57 
     [views] => 3 
     [username] => Fire G 
    ) 

[4] => Array 
    (
     [id] => 6 
     [post_id] => 396 
     [user_id] => 1 
     [view_date] => 2010-11-19 23:07:55 
     [views] => 3 
     [username] => Fire G 
    ) 

[5] => Array 
    (
     [id] => 5 
     [post_id] => 396 
     [user_id] => 1 
     [view_date] => 2010-11-19 23:07:52 
     [views] => 3 
     [username] => Fire G 
    ) 

[6] => Array 
    (
     [id] => 4 
     [post_id] => 13 
     [user_id] => 1 
     [view_date] => 2010-11-19 22:59:35 
     [views] => 1 
     [username] => Fire G 
    ) 

[7] => Array 
    (
     [id] => 3 
     [post_id] => 3 
     [user_id] => 1 
     [view_date] => 2010-11-19 22:59:28 
     [views] => 1 
     [username] => Fire G 
    ) 

[8] => Array 
    (
     [id] => 2 
     [post_id] => 398 
     [user_id] => 1 
     [view_date] => 2010-11-18 11:37:20 
     [views] => 4 
     [username] => Fire G 
    ) 

[9] => Array 
    (
     [id] => 1 
     [post_id] => 398 
     [user_id] => 1 
     [view_date] => 2010-11-18 11:37:16 
     [views] => 4 
     [username] => Fire G 
    ) 
) 

回答

6

使用uasort,用戶自定義排序,讓你提供你自己的函數來定義一個元素是否應該在另一個之前到來。

http://www.php.net/manual/en/function.uasort.php

你比較器功能會是這樣的

function cmp($a, $b) { 
    return $a['post_id'] > $b['post_id'] ? 1 : -1; 
} 
+0

+1太棒了!那麼'$ a ['post_id'] - $ b ['post_id']'? – alex 2010-11-22 01:44:32

+0

我不知道那是什麼意思。帖子ID之間的代數差異? – 2010-11-22 01:45:54

+0

@Dan Grossman對不起,我的意思是,如果你返回一個減去另一個,它會給出一個負面或正面,如果他們不同,或0,如果他們是相同的。有效地滿足排序回調的要求。 – alex 2010-11-22 02:45:57