开发者

PHP sorting an array by mysql date

开发者 https://www.devze.com 2022-12-27 07:57 出处:网络
I have an array that I would like to sort using a date field from a MySQL database. Here is a sample of the array which is named news in my class:

I have an array that I would like to sort using a date field from a MySQL database.

Here is a sample of the array which is named news in my class:

[48] => Array
    (
        [id] => 14
        [type] => 3
        [updated] => 2010-04-17 13:54:42
    )

[49] => Array
    (
        [id] => 15
        [type] => 3
        [updated] => 2010-04-17 13:57:21
    )

I want to sort by the updated field.

I have some code I have started but am unsure how to complete it and get it working.

class Proce开发者_运维百科ssClass {
  // ....
  function sortNews($x)
  {
    usort($this->news, array("ProcessClass", "cmp")); //correct sort type?
  }

  function cmp($a, $b)
  {
    //  missing code
  }

Can anyone help??


In most cases, will be easier to add ORDER BY updated to the end of the SQL query, however if your data is coming from multiple sources and you need to resort in PHP, you can use usort() to sort an array based on a user defined function. To use a class function for comparison, the function MUST be static. It can simply compare the updated value in the array using the function strcmp() which happens to return exactly what you need to sort by a MySQL formatted date:

class ProcessClass {
  // this must be static
  static function sort_by_updated($a, $b)
  {
    return strcmp($a['updated'], $b['updated']);
  }

  function sortNews()
  {
    usort($this->news, array("ProcessClass", "sort_by_updated")); 
  }

If you want to reverse sort order, simply swap the comparison params: return strcmp($b['updated'], $a['updated'])


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 (str_to_upper($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));


If you really need to use PHP sorting, you could go for a usort() implementation.

<?php
function mysql_datesort($a, $b)
{
    if ($a == $b) {
        return 0;
    }

    return ($a->date_field < $b->date_field) ? -1 : 1; //custom check here
}

$a = array(); //your PHP array here...

usort($a, "mysql_datesort");

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消