按日期时间在PHP中对数组中的数组进行排序

时间:2012-04-05 19:25:03

标签: php arrays datetime sorting

我目前在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)

5 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分:2)

按指定的mysql datetime字段和顺序对记录数组/ 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));

答案 2 :(得分:1)

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

答案 3 :(得分: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 manpage

答案 4 :(得分: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;
}