PHP Organize Date Variables
Put them in an array as datetime objects or maybe build a string in the form YYYYMMDD (add zeroes where necessary). With strings in each array
If you use strings, you can do a simple sort. With datetime objects, you can create a custom sort function :
<?php
$the_array = array();
$the_array[] = [1, new Datetime('2016-04-30')]; // year , month , day
$the_array[] = [2, new Datetime('2016-03-25')]; // year , month , day
// add the others
$the_array[] = [5,new Datetime('2016-04-12')]; // year , month , day
// show the contents of the array
var_dump($the_array);
// sort the array using a callback function
function compare_array_entries($a, $b) {
// $a = one entry in array, $b = following entry in array
// [0] = the number , [1] = the datetime object
if ($a[1] == $b[1]) {
return 0;
}
return ($a[1]< $b[1]) ? -1 : 1;
}
// now do the actual sorting using the callback function above to actually compare two entries at a time
usort($the_array,'compare_array_entries');
// dump the array contents again
var_dump($the_array);
// now you can use something like foreach ($the_array as $key = > $value) { } to go through the array. , $value[0] is your number, $value[1] is your datetime object
?>
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now