Prev | Current Page 221 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


if($a == $b) return 0;
// Disassemble dates
list($amonth, $aday, $ayear) = explode('-',$a);
list($bmonth, $bday, $byear) = explode('-',$b);
// Pad the month with a leading zero if leading number not present
$amonth = str_pad($amonth, 2, "0", STR_PAD_LEFT);
$bmonth = str_pad($bmonth, 2, "0", STR_PAD_LEFT);
// Pad the day with a leading zero if leading number not present
$aday = str_pad($aday, 2, "0", STR_PAD_LEFT);
$bday = str_pad($bday, 2, "0", STR_PAD_LEFT);
// Reassemble dates
$a = $ayear . $amonth . $aday;
$b = $byear . $bmonth . $bday;
// Determine whether date $a > $date b
return ($a > $b) ? 1 : -1;
}
usort($dates, 'DateSort');
CHAPTER 5 ?–  ARRAYS 153
echo "

Sorting the array using the user-defined DateSort() function:

";
print_r($dates);
?>
This returns the following (formatted for readability):
Sorting the array using the sort() function:
Array ( [0] => 1-01-2005 [1] => 10-10-2003 [2] => 10-10-2004
[3] => 2-16-2003 [4] => 2-17-2002 )
Sorting the array using the natsort() function:
Array ( [0] => 1-01-2005 [3] => 2-16-2003 [4] => 2-17-2002
[1] => 10-10-2003 [2] => 10-10-2004 )
Sorting the array using the user-defined DateSort() function:
Array ( [0] => 2-17-2002 [1] => 2-16-2003 [2] => 10-10-2003
[3] => 10-10-2004 [4] => 1-01-2005 )
Merging, Slicing, Splicing, and Dissecting Arrays
This section introduces a number of functions that are capable of performing somewhat
more complex array-manipulation tasks, such as combining and merging multiple
arrays, extracting a cross-section of array elements, and comparing arrays.


Pages:
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233