0

我有这样的输入:

array
   0 => 
      array
          'task_uid' => '10214' 
          'createdate' => '2012-04-18 09:47:40'
          'task_id' => '92966' 
   1 => 
      array
          'task_uid' => '10214' 
          'createdate' => '2012-04-18 09:47:40' 
          'task_id' => '92967' 

我必须通过 createdate 以稳定的方式对其进行排序。我创建了这个函数:

function compareTime($a, $b) {
    $a_timestamp = strtotime($a["createdate"]);
    $b_timestamp = strtotime($b["createdate"]);
    if ($a_timestamp > $b_timestamp)
        return -1;
    else if ($a_timestamp < $b_timestamp)
        return 1;
    else
        return 0;
    //return strcmp($a["createdate"], $b["createdate"]);
}

usort($input, array( $this, "compareTime"));

它应该从最旧到最新排序,但这是混合数据。此外,如果 datacreate 相同,则不要更改位置。但是如果我在 compareTime 中使用:

return strcmp($a["createdate"], $b["createdate"]);

然后它从示例中更改元素(这对我来说是错误的)。你能给我答案我应该如何对输入进行排序?

4

1 回答 1

1
function cmp($a, $b)
{
    $a = strtotime($a['createdate']);
    $b = strtotime($b['createdate']);

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($input, "cmp");

print_r($input);

输出(从最旧到最新)

Array
(
    [0] => Array
        (
            [task_uid] => 10214
            [createdate] => 2012-04-18 09:47:40
            [task_id] => 92967
        )

    [1] => Array
        (
            [task_uid] => 10214
            [createdate] => 2012-04-19 09:47:40
            [task_id] => 92966
        )

    [2] => Array
        (
            [task_uid] => 9999
            [createdate] => 2012-04-22 09:47:40
            [task_id] => 9999
        )

)

键盘演示


如果你想在一个类中进行排序,例如使用类的方法进行比较,可以这样做:

class MyTest
{
    public function __construct()
    {
        $input = array(
           0 => 
              array(
                  'task_uid' => '10214',
                  'createdate' => '2012-04-19 09:47:40',
                  'task_id' => '92966'),
           1=>   array(
                  'task_uid' => '9999',
                  'createdate' => '2012-04-22 09:47:40',
                  'task_id' => '9999'),
           2 => 
              array(
                  'task_uid' => '10214' ,
                  'createdate' => '2012-04-18 09:47:40' ,
                  'task_id' => '92967' )
        );

        usort($input, array($this, "cmp"));

        print_r($input);
    }

    public function cmp($a, $b)
    {
        $a = strtotime($a['createdate']);
        $b = strtotime($b['createdate']);

        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
}

$obj = new MyTest();

输出与第一个示例相同。

于 2012-11-23T10:40:12.277 回答