Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: sort array by half-hour intervals
    text
    copied!<p>I have a very specific problem here. I have a multi-dimensional array that I want to sort first by half-hour time intervals, second by dates. The function <a href="http://us2.php.net/manual/en/function.array-multisort.php" rel="nofollow noreferrer">array_multisort</a> will not meet my requirements.</p> <p>Example: I want:</p> <pre><code>array(array("time"=&gt;"12:15", "date"=&gt;"2009-03-24"), array("time"=&gt;"12:10", "date"=&gt;"2009-03-23"), array("time"=&gt;"12:00", "date"=&gt;"2009-03-24"), array("time"=&gt;"11:30", "date"=&gt;"2009-03-24")); </code></pre> <p>To end up as:</p> <pre><code>array(array("time"=&gt;"11:30", "date"=&gt;"2009-03-24"), array("time"=&gt;"12:10", "date"=&gt;"2009-03-23"), array("time"=&gt;"12:00", "date"=&gt;"2009-03-24"), array("time"=&gt;"12:15", "date"=&gt;"2009-03-24")); </code></pre> <p>I've tried to accomplish this with <a href="http://php.net/manual/en/function.uksort.php" rel="nofollow noreferrer">uksort</a> in combination with my own sorting callback function. This is the code I am currently using:</p> <pre><code>uksort($myArray, "sortThirties"); function sortThirties($a, $b) { //Get the two times as timestamps relative to today $one = strtotime($a['time']); $two = strtotime($b['time']); //Round them down to the nearest half-hour time $one = $one - ($one % 1800); $two = $two - ($two % 1800); //Return the difference if times are unequal //If times are equal, return the difference between dates. return ($one == $two ? strcmp($a['date'],$b['date']) : $one - $two); } </code></pre> <p>Immediately after running this function, I print out the array with print_r(), and the order of the data appears to be random. What am I missing?</p> <p><strong>EDIT</strong>: It turns out, the order <strong>is</strong> <em>completely</em> random. I added this line to the sortThirties function:</p> <pre><code>echo "&lt;BR&gt;",$a['time']," ",$b['time']; </code></pre> <p>and all I got was 50 pages of <code>&lt;BR&gt;</code>'s.</p> <p>I know the array is correctly structured because this code executed on the very same array gives me the unsorted data:</p> <pre><code>foreach($myArray AS $a) { echo "&lt;BR&gt;",$a['date']," ",$a['time']; } </code></pre> <p>The only thing I can think of is there must be a problem with uksort. Any thoughts?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload