PHP Sort a multidimensional array by element containing date

后端 未结 10 1729
野趣味
野趣味 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: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)
    

提交回复
热议问题