对合并递归数组进行排序

时间:2012-02-07 02:38:41

标签: php arrays sorting

我已经使用php函数“merge_recursive”合并了两个数组(两者都来自sql查询)所有这些都有一个公共字段[date]是否可以按[date]字段对数组[new]进行排序?

       [new] => Array
            (
                [0] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [favorite_id] => 2
                        [date] => 1328579091
                        [images_id] => 4
                        [image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [text] => 
                        [favorite_user] => 8888
                        [favorite_user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                    )

                [1] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [favorite_id] => 5
                        [date] => 1328578954
                        [images_id] => 2
                        [image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
                        [text] => 3
                        [favorite_user] => 6666
                        [favorite_user_image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
                    )

                [2] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [image_id] => 4
                        [date] => 1328579081
                        [text] => 
                        [image_date] => 1328577934
                        [comments] => 0
                    )

            )

我希望aray类似于(例如下面的)

[1] = Array
(
)
[0] = Array
(
)
[2] = Array
(
)

有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用array_multisort,这完全符合您的要求。

$dates = array();
foreach ($new as $key => $value) { // $new is your array
    $dates[$key] = $value['date'];
}
array_multisort($dates, SORT_ASC, $new);

这可以通过多种排序标准轻松扩展。

答案 1 :(得分:0)

您可以尝试这样的事情:

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

function compareDate($a, $b) {
    if ($a["date"] == $b["date"]) {
        return 0;
    }
    return ($a["date"] < $b["date"]) ? -1 : 1;
}

uasort($input, compareDate);