Reputation: 11911
I have an array that returns a list of times, but it puts in an order like this 01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, 10:00:00, 11:00:00, 12:00:00
I am looking to change the order of this to 10:00:00, 11:00:00, 12:00:00, 01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00
What would be the best way to go about this?
Here is my PHP code:
foreach($thursday as $y => $x){
echo '<tr>';
foreach($x as $a => $b){
echo '<td>' . $b . '</td>';
}
echo '</tr>';
}
the $b is the times.
Any suggestions?
Upvotes: 0
Views: 80
Reputation: 769
This is just a suggestion. If you're receiving always the array like: 01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, 10:00:00, 11:00:00, 12:00:00
(I mean, hourly ordered), just in this case you can simple make another array.
<?php
//array with dates.
$dates = array("01:00:00", "02:00:00", "03:00:00", "04:00:00", "05:00:00", "10:00:00", "11:00:00", "12:00:00");
// get the first 5 hours.
$newarray = array_slice($dates, 0, 5 );
// get the last 3 hours.
$newarray2 = array_slice($dates, 5, 8);
// now, merge it, putting the last 3 in the start.
$dates = array_merge($newarray2, $newarray); // and we're done.
Upvotes: 0
Reputation: 16214
One of the ways is just 'temporary' increase of time below '10' into the 'next' day while sorting )) If you want to deal with 09 or 08, just modify the condition.
$data = explode(', ', '01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, ' .
'10:00:00, 11:00:00, 12:00:00');
usort($data, function($el1, $el2) {
if ($el1[0] == '0')
$el1 = strtotime($el1 . ' +1 day');
else
$el1 = strtotime($el1);
if ($el2[0] == '0')
$el2 = strtotime($el2 . ' +1 day');
else
$el2 = strtotime($el2);
return $el1 > $el2;
});
var_dump($data);
Result
array(8) {
[0]=>
string(8) "10:00:00"
[1]=>
string(8) "11:00:00"
[2]=>
string(8) "12:00:00"
[3]=>
string(8) "01:00:00"
[4]=>
string(8) "02:00:00"
[5]=>
string(8) "03:00:00"
[6]=>
string(8) "04:00:00"
[7]=>
string(8) "05:00:00"
}
Upvotes: 2
Reputation: 16502
This is a very particular solution, but check for the first character to see if it's equal to 1 and output it if so, if not, put it in a buffer to display later after the foreach
has completed.
$append = '';
foreach ($x as $a => $b) {
if (substr($b, 0, 1) === '1') {
echo '<td>'.$b.'</td>';
} else {
$append .= '<td>'.$b.'</td>';
}
}
echo $append;
From the best I can see, you're trying to sort ascending time from a particular time. Here's a function for that:
function sortAscendingFromTime($array, $time = '00:00:00') {
function cmp($a, $b) {
if (strtotime($a) == strtotime($b)) {
return 0;
}
return (strtotime($a) < strtotime($b)) ? -1 : 1;
}
uasort($array, 'cmp');
$newArray = array();
$endArray = array();
$timestamp = strtotime($time);
foreach ($array as $a) {
if (strtotime($a) < $timestamp) {
$endArray[] = $a;
} else {
$newArray[] = $a;
}
}
return array_merge($newArray, $endArray);
}
Upvotes: 0