本文介绍了按日期排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我被从MySQL中获取数据,并在一个阵列中合并以下三个查询结果建立一个数组。

I've got a question. I'm building an array by getting data from mysql and merging three query results in one array.

我把数据数组是这样的:

I put data to array like this:

while ($a = mysql_fetch_object($activities)) {
            $a->type = 1;
            $array1[] = $a;
        }
        while ($k = mysql_fetch_object($fuups)) {
        $k->type = 2;
            $array1[] = $k;
        }
        while ($x = mysql_fetch_object($refuups)) {
            $x->type = 3;
            $array1[] = $x;
        }

        return (object)$array1;

这将返回是这样的:

stdClass Object
(
    [0] => stdClass Object
        (
            [added] => 2012-01-17 07:33:53
            [type] => 1
        )

    [1] => stdClass Object
        (
            [added] => 2012-01-13 06:36:22
            [type] => 1
        )

    [2] => stdClass Object
        (
            [added_type_2] => 2012-01-09 04:01:12
            [type] => 2
        )

    [3] => stdClass Object
        (
            [added_type_2] => 2012-02-08 02:08:32
            [type] => 2
        )

    [4] => stdClass Object
        (
            [added_type_2] => 2012-01-25 00:09:08
            [type] => 2
        )

    [5] => stdClass Object
        (
            [added_type_3] => 2012-01-23 00:09:08
            [type] => 3
        )

    [6] => stdClass Object
        (
            [added_type_3] => 2012-01-22 00:09:08
            [type] => 3
        )

)

我试过之类的东西ASORT,ksort,排序但没有运气。还通过添加倒序渐与日期谢谢

I tried things like asort, ksort, sort but no luck. also getting the dates with "order by added desc" thank you

推荐答案

您可以使用usort()如果你改变读取对象来获取assoc命令:

You can use usort() if you change fetch object to fetch assoc:

function my_date_sort($a,$b) {
   if(isset($a[0]) && isset($b[0])) {
       $a = strtotime($a[0]); // optionally convert to time
       $b = strtotime($b[0]);
       if($a == $b) return 0;
       else return ($a > $b) ? 1 : -1;
   } else { // no valid subs, change this to put empty ones on top or bottom
       return 1; // put at bottom, -1 would put at top.
}


usort($results, 'my_date_sort');

好运...

这篇关于按日期排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:51