Sorting an array with DateTime strings?

后端 未结 6 1345
深忆病人
深忆病人 2021-01-20 03:57

How can i sort efficiently this array (recent items first) on end_time value in PHP?

array
  0 => 
    array
      \'value\' => int 4
             


        
相关标签:
6条回答
  • 2021-01-20 04:28

    Have you looked at the usortDocs function? It lets you define a callback function to compare two values. So I'm suggesting something along these lines:

    function compare_func($a, $b)
    {
        // CONVERT $a AND $b to DATE AND TIME using strtotime() function
        $t1 = strtotime($a["end_time"]);
        $t2 = strtotime($b["end_time"]);
    
        return ($t2 - $t1);
    }
    
    usort(main_array, "compare_func");
    
    0 讨论(0)
  • 2021-01-20 04:43
    usort($data, function($a, $b) {
        return strtotime($a['end_time']) - strtotime($b['end_time']);
    });
    
    0 讨论(0)
  • 2021-01-20 04:46

    Try:

    
    function sort_datewise($x, $y) {
        $t1 = strtotime($x['end_time']);
        $t2 = strtotime($y['end_time']);
        return $t1 - $t2;
    }    
    usort($array, 'sort_datewise');
    
    
    0 讨论(0)
  • 2021-01-20 04:49
    usort($array, function($a, $b){ 
        return (strtotime ($a ['end_time']) 
              - strtotime ($b ['end_time'])) 
              * -1; 
    });
    
    0 讨论(0)
  • 2021-01-20 04:53

    Is this data coming from a database? If it is then the best approach is simply have the database do the sorting for you.

    0 讨论(0)
  • 2021-01-20 04:55

    You can use uasort function like this:

    $arr=array();
    $arr[] = array('valeu' => "4", 'end_time' => '2012-01-20T08:00:00+0000');
    $arr[] = array('valeu' => "0", 'end_time' => '2012-01-21T08:00:00+0000');
    $arr[] = array('valeu' => "5", 'end_time' => '2012-01-22T08:00:00+0000');
    $arr[] = array('valeu' => "4", 'end_time' => '2012-01-23T08:00:00+0000');
    $arr[] = array('valeu' => "7", 'end_time' => '2012-01-24T08:00:00+0000');
    print_r($arr);
    function cmp($a, $b) {
        $ta = strtotime($a['end_time']);
        $tb = strtotime($b['end_time']);
        return ($ta - $tb);
    }
    uasort($arr, 'cmp');
    print_r($arr);
    
    0 讨论(0)
提交回复
热议问题