Wednesday, February 25, 2009

Sorting an array by key on day, month, year or time


function date_compare($x, $y){
  $x = strtotime($x);
  $y = strtotime($y);
  if ($x == $y) return 0;
  return (($x > $y)?1:-1);
}
$array = array (
  'Jan 01, 2008' => 1,
  'Oct 31, 2008' => 10,
  'Nov 01, 2008' => 11,
  'Dec 01, 2008' => 12,
  'Jul 01, 2008' => 7,
  'Aug 01, 2008' => 8,
  'Sep 01, 2008' => 9,
);

Before sorting print the array

print_r($array);

Now Sort the array

uksort($array, 'date_compare');

After sorting print the array

print_r($array);

Sorting an array by time, date, month or year


function date_compare($x, $y){
  $x = strtotime($x);
  $y = strtotime($y);
  if ($x == $y) return 0;
  return (($x > $y)?1:-1);
}
$array = array (
 'Jan 01, 2008',
 'Oct 31, 2008',
 'Nov 01, 2008',
 'Dec 01, 2008',
 'Jul 01, 2008',
 'Aug 01, 2008',
 'Sep 01, 2008'
);

Before sorting print the array

print_r($array);

Now Sort the array

usort($array, 'date_compare');

After sorting print the array

print_r($array);