PHP Sort a multidimensional array by element containing date

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

提交回复
热议问题