PHP Sort a multidimensional array by element containing date

后端 未结 10 1733
野趣味
野趣味 2020-11-22 09:02

I have an array such as:

Array
(
[0] => Array
    (
        [id] => 2
        [type] => comment
        [text] => hey
        [datetime] => 20         


        
相关标签:
10条回答
  • 2020-11-22 09:43

    For those still looking a solved it this way inside a class with a function sortByDate, see the code below

    <?php
    
    class ContactsController 
    {
        public function __construct()
        {
        //
        }
    
    
        function sortByDate($key)
        {
            return function ($a, $b) use ($key) {
                $t1 = strtotime($a[$key]);
                $t2 = strtotime($b[$key]);
                return $t2-$t1;
            };
    
        }
    
        public function index()
        {
    
            $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-11 12:38:23','created_at' =>'2020-06-11 12:38:23');
            $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-16 12:38:23','created_at' =>'2020-06-10 12:38:23');
            $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-7 12:38:23','created_at' =>'2020-06-9 12:38:23');
    
    
            usort($data, $this->sortByDate('updated_at'));
    
            //usort($data, $this->sortByDate('created_at'));
            echo $data;
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:46

    From php7 you can use the Spaceship operator:

    usort($array, function($a, $b) {
      return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
    });
    
    0 讨论(0)
  • 2020-11-22 09:48

    $array = Array
    (
      [0] => Array
       (
        [id] => 2
        [type] => comment
        [text] => hey
        [datetime] => 2010-05-15 11:29:45
       )
    
     [1] => Array
      (
        [id] => 3
        [type] => status
        [text] => oi
        [datetime] => 2010-05-26 15:59:53
      )
    
      [2] => Array
       (
        [id] => 4
        [type] => status
        [text] => yeww
        [datetime] => 2010-05-26 16:04:24
       )
    
       );
       print_r($array);   
       $name = 'datetime';
       usort($array, function ($a, $b) use(&$name){
          return $a[$name] - $b[$name];});
    
       print_r($array);
    
    0 讨论(0)
  • 2020-11-22 09:52

    I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.

    So I research the php.net website and end up doing this:

    class MyClass {
       public function getItems(){
          usort( $this->items, array("MyClass", "sortByTime") );
          return $this->items;
       }
       public function sortByTime($a, $b){
          return $b["time"] - $a["time"];
       }
    }
    

    You can find very useful examples in the PHP.net website

    My array looked like this:

      'recent' => 
        array
          92 => 
            array
              'id' => string '92' (length=2)
              'quantity' => string '1' (length=1)
              'time' => string '1396514041' (length=10)
          52 => 
            array
              'id' => string '52' (length=2)
              'quantity' => string '8' (length=1)
              'time' => string '1396514838' (length=10)
          22 => 
            array
              'id' => string '22' (length=2)
              'quantity' => string '1' (length=1)
              'time' => string '1396514871' (length=10)
          81 => 
            array
              'id' => string '81' (length=2)
              'quantity' => string '2' (length=1)
              'time' => string '1396514988' (length=10)
    
    0 讨论(0)
  • 2020-11-22 09:53

    Sorting array of records/assoc_arrays by specified mysql datetime field and by order:

    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 (strtoupper($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));
    
    0 讨论(0)
  • 2020-11-22 09:55

    Use usort() and a custom comparison function:

    function date_compare($a, $b)
    {
        $t1 = strtotime($a['datetime']);
        $t2 = strtotime($b['datetime']);
        return $t1 - $t2;
    }    
    usort($array, 'date_compare');
    

    EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.

    usort will pass two of these records to the given comparison function date_compare() at a a time. date_compare then extracts the "datetime" field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0 if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort() uses this information to sort the array.

    0 讨论(0)
提交回复
热议问题