5

我目前在 PHP 中有一个问题,我想按创建日期对这些帖子进行排序,以便它们可以按降序显示。我一直在寻找一个 PHP 函数来做到这一点,但没有运气。

有一个简单的解决方案吗?任何想法将不胜感激:)

array
      0 => 
        array
          'post_id' => string '1' (length=1)
          'user_id' => string '3' (length=1)
          'post' => string 'this is a post' (length=14)
          'created' => string '2012-04-05 20:11:38' (length=19)
     1 => 
        array
          'post_id' => string '2' (length=1)
          'user_id' => string '2' (length=1)
          'post' => string 'this is a post' (length=14)
          'created' => string '2012-04-05 20:11:38' (length=19)
     2 => 
        array
          'post_id' => string '3' (length=1)
          'user_id' => string '5' (length=1)
          'post' => string 'this is a post' (length=14)
          'created' => string '2012-04-05 20:11:38' (length=19)
4

5 回答 5

5

试试这个:

<?php
$a=array(
      0 => 
        array(
          'post_id' => '1',
          'user_id' => '3',
          'post' => 'this is a post',
          'created' => '2012-04-05 20:11:40'
          ),
     1 => 
        array(
          'post_id' => '2',
          'user_id' => '2',
          'post' => 'this is a post',
          'created' => '2012-04-05 20:11:39'
          ),
     2 => 
        array(
          'post_id' => '3',
          'user_id' => '5',
          'post' => 'this is a post',
          'created' => '2012-04-05 20:11:38'
          )
);
function cmp($a,$b){
    return strtotime($a['created'])<strtotime($b['created'])?1:-1;
};

uasort($a,'cmp');
print_r($a);
?>
于 2012-04-05T19:38:04.450 回答
2

按指定的mysql日期时间字段和顺序对记录/ assoc_arrays数组进行排序:

    function build_sorter($key, $dir='ASC') {
        return function ($a, $b) use ($key, $dir) {
            $t1=strtotime(is_array($a)?$a[$key]:$a->$key);
            $t2=strtotime(is_array($b)?$b[$key]:$b->$key);
            if($t1==$t2) return 0;
            return (str_to_upper($dir)=='ASC'?($t1 < $t2):($t1 > $t2)) ? -1 : 1;
        };
    }


    // $sort - key or property name 
    // $dir - ASC/DESC sort order or empty
    usort($arr, build_sorter($sort, $dir));
于 2013-11-20T11:53:51.960 回答
1

您可以使用strtotime()将时间戳转换为整数。

于 2012-04-05T19:27:38.520 回答
1

您可以使用自定义排序函数对数组进行排序,如下所示:

function cmp($a, $b) {
    if($a['created'] < $b['created']) {
        return 1;
    } else if ($a['created'] > $b['created']) {
        return -1;
    } else  {
        // The only option left is that they are equal
        return 0;
    }
}

usort($array, cmp);

有关 usort 的更多信息,请查看php 手册页

于 2012-04-05T19:38:37.540 回答
1

您可以使用usort()函数,该函数允许您根据自己的标准对数组进行排序。

function cmp($a, $b)
{
    if ($a['created'] == $b['created']) {
        return 0;
    }

    return ($a['created'] < $b['created']) ? 1 : -1;
}

usort($myArray, "cmp");

print_r($myArray);

或者,如果您想转换为时间:

function cmp($a, $b)
{
    if ($a['created'] == $b['created']) {
        return 0;
    }

    $aInt = strtotime($a['created']);
    $bInt = strtotime($b['created']);

    return ($aInt < $bInt) ? 1 : -1;
}
于 2012-04-05T19:40:04.550 回答