按子值排序父数组

时间:2010-11-22 01:30:10

标签: php arrays multidimensional-array sorting

如何通过任何子值(即:post_id,username等等)对下面的数组进行排序?

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
    )
)

1 个答案:

答案 0 :(得分:6)

使用uasort用户定义的排序,它允许您提供自己的函数来定义一个元素是否应该先于另一个元素。

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

您的比较器功能类似于

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