Order By

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gmitra
Forum Newbie
Posts: 15
Joined: Tue Jul 02, 2002 7:45 pm
Location: New York

Order By

Post by gmitra »

How do you sort data by date in the form month/day/year (xx/xx/xxxx). Right now I've got my data sorted by Date Desc. So it would go, for example....

05/21/2002
05/14/2002
02/12/2002

But now lets say we throw in the date 07/24/1999. Since PHP sorts by the month and day first 07/24/1999 would go up top instead of on the bottom. Does anyone know how remedy this situation?
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

Try the usort() function:

Code: Select all

<?php
$dates = array(
	'05/21/2002',
	'05/14/2002',
	'02/12/2002',
	'07/24/1999',
);

usort($dates, "sort_date");

function sort_date($a, $b)
&#123;
	// The "Regular Expression" for preg_match():
	$re = '(&#1111;0-9]&#1111;0-9])\/'.
		'(&#1111;0-9]&#1111;0-9])\/'.
		'(&#1111;0-9]&#1111;0-9]&#1111;0-9]&#1111;0-9])';

	// Get month, day, year of $a and $b:
	preg_match("/$re/", $a, $a_date);
	preg_match("/$re/", $b, $b_date);

	// $X_date now has 1=month, 2=day, 3=year

	// Compare both yyyy/mm/dd strings:
	return strcmp(
		"$a_date&#1111;3]/$a_date&#1111;1]/$a_date&#1111;2]",
		"$b_date&#1111;3]/$b_date&#1111;1]/$b_date&#1111;2]");
&#125;

print_r($dates);
?>
If any dates are invalid, add this:

Code: Select all

// Get month, day, year of $a and $b:
	$a_is_date = preg_match($re, $a, $a_date);
	$b_is_date = preg_match($re, $b, $b_date);

	if (!$a_is_date || !$b_is_date)
	&#123;
		if (!$a_is_date && !$b_is_date)
			return strcmp($a, $b);

		if (!$a_is_date) return -1;
		if (!$b_is_date) return 1;
	&#125;
User avatar
gmitra
Forum Newbie
Posts: 15
Joined: Tue Jul 02, 2002 7:45 pm
Location: New York

Post by gmitra »

Nevermind, I've solved my problem by simply adding an extra column into my database (num) and ordering by the num variable. Thanks for the help anyway though! :)
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You could also save your date as a timestamp, that'll make it an integer and easier to sort and format and do calculations with.

Mac
Post Reply