up vote 0 down vote favorite

Hi

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 ProcessClass {
  // ....
  function sortNews($x)
  {
    usort($this->news, array("ProcessClass", "cmp")); //correct sort type?
  }

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

Can anyone help??

flag
1  
why not to sort already in mysql? – Col. Shrapnel Apr 20 at 17:33
Can not you sort in MySQL side ? – hsz Apr 20 at 17:35
Sorry I should have said, the array is built from about 5 different SQL select queries, that differ in various circumstances so can not be joined. – daviemanchester Apr 20 at 17:45
@daviemanchester - You could still edit that into your question! Thanks for asking on stack overflow! – gnarf Apr 20 at 17:51

2 Answers

up vote 4 down vote

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'])

link|flag
2  
Agreed, get the database to sort, that's what databases are good for. – ilikeorangutans Apr 20 at 17:38
Sorry I should have said, the array is built from about 5 different SQL select queries, that differ in various circumstances so can not be joined. – daviemanchester Apr 20 at 17:44
Worked great thanks!! – daviemanchester Apr 20 at 20:23
up vote 0 down vote

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");

?>
link|flag
Thanks for the help. – daviemanchester Apr 20 at 20:24

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.