I am trying to sort an array based on time. The array looks like this


[0] => Array
        (
            [0] => 11:45:00
            [1] => Hull Middle School
            [2] => X
            [3] => S
        )

[1] => Array
    (
        [0] => 09:00:00
        [1] => Hull Middle School
        [2] => S
        [3] => V
    )

[2] => Array
    (
        [0] => 14:30:00
        [1] => Hull Middle School
        [2] => S
        [3] => W

I've tried various sorts: sort, asort, natcasesort, etc, but nothing seems to work. Not sure what else to try.

Suggestions?

    I'd use [man]usort/man, as you'll need to define a sort function that looks at sub-array element 0 to compare the times.

      Yeah, you can always define your own comparator class/methods to handle this kind of custom sorting.

        This would be an example of why UNIX timestamps were invented ... you just SORT_NUMERIC them.

        Of course, you may not have control of your data 😉

          In this situation it is best to create an associative array, The key for each array could be array slot [0] converted into a unix timestamp. Then you could use ksort() which sorts an array by keys. What this will allow you to do is sort the array's by time so that each slot is also in the proper order.

            dalecosp;11026455 wrote:

            This would be an example of why UNIX timestamps were invented ... you just SORT_NUMERIC them.

            Of course, you may not have control of your data 😉

            I don't think that's an issue here -- as long as the times are based on a 24-hour clock and all numbers are zero-padded, in which case a normal string compare should work just fine. The primary issue, I believe, is just dealing with the fact that it's a multi-dimension array, so you need to let PHP know which sub-element needs to be compared (which I personally find easier to do with usort() than with array_multi_sort()).

            <?php
            
            $theArray = array(
            	array(
            		'11:45:00',
            		'Hull Middle School',
            		'X',
            		'S'
            	),
            	array(
            		'09:00:00',
            		'Hull Middle School',
            		'S',
            		'V'
            	),
            	array(
            		'14:30:00',
            		'Hull Middle School',
            		'S',
            		'W'
            	)
            );
            echo "<pre>".print_r($theArray,1)."</pre>\n";
            usort(
            	$theArray,
            	function ($a, $b)
            	{
            		return strcmp($a[0], $b[0]);
            	}
            );
            echo "<pre>".print_r($theArray,1)."</pre>\n";
            
              10 days later

              Thank you for your replies. I think nogDog is closest to a workable solution; however, somethings causing the code to crash. I narrowed the problem down to

               
              usort(
                  $theArray,
                  function ($a, $b)
                  {
                      return strcmp($a[0], $b[0]);
                  }
              );
              

              What am I missing here?

                How you're using the code, and a description of the "crash".

                  How you're using the code, and a description of the "crash".

                  If I comment out the usort portion of the code, the rest of the page works. So something in that block is wrong. Here's the complete code (obviously a mock up. The data is actually in a table).

                  $theArray = array(
                      array(
                          '11:45:00',
                          'Hull Middle School',
                          'X',
                          'S'
                      ),
                      array(
                          '09:00:00',
                          'Hull Middle School',
                          'S',
                          'V'
                      ),
                      array(
                          '14:30:00',
                          'Hull Middle School',
                          'S',
                          'W'
                      )
                  );
                  
                  echo "<pre>".print_r($theArray,1)."</pre>\n";
                  usort(
                      $theArray,
                      function ($a, $b)
                      {
                          return strcmp($a[0], $b[0]);
                      }
                  );
                  
                  echo "<pre>".print_r($theArray,1)."</pre>\n";
                  
                  

                    Well, that's half of what is missing (the code), but there is still no description of what the "crash" looks like (your posted code works for me).

                      What version of PHP are you using? If it's not reasonably recent, you'll either need to use create_function() within the usort(), or else define the actual sorting function outside of the usort() and reference the function's name as the second parameter for usort().

                        "Relatively Recent" being >= 5.4, right?

                          dalecosp;11026985 wrote:

                          "Relatively Recent" being >= 5.4, right?

                          5.3.0, I believe.

                            Hmm, I guess I misinterpreted the handbook then. I can confirm by direct test that it doesn't work on 5.2.17 and it does on 5.3.8 --- if that helps anyone.

                              [man]functions.anonymous[/man] reports that in version 5.3.0, "Anonymous functions become available." Thus, "relatively recent" can be defined as "any PHP version released on or after 30-Jun-2009."

                                Sometimes when you're using new code on an old version of PHP the problem is because you're using an old version of PHP.

                                If it's PHP 5.2.x there would be a Parse error reporting an "unexpected T_FUNCTION".

                                NogDog wrote:

                                or else define the actual sorting function outside of the usort() and reference the function's name as the second parameter for usort().

                                Some simple-minded tests I did just now suggest that closures are about an order of magnitude slower than named functions/methods. The difference can be significant if the array being sorted is big, so passing names might be preferable unless you're importing variables from an enclosing scope. (Not all the time, of course: YMMV and all that, and you still can't call a private method from outside its class.)

                                  dalescosp: I can confirm by direct test that it doesn't work on 5.2.17 and it does on 5.3.8

                                  My php's version is 5.2. That's probably the reason my code is not executing correctly. Not sure how to write a function that sorts by time.

                                  robkir

                                    And see NogDog's earlier post (was it NogDog?) ... he gave one.

                                    All you should have to do is take the generic "function" he put in the call to usort elsewhere in your script, give it a meaningful name, and then pass that name as a parameter to usort as shown in the manual (the link which Mr. Weedpacket just provided).

                                      It is working. Thanks.

                                      $theArray = array(
                                          array(
                                              '11:45:00',
                                              'Hull Middle School',
                                              'X',
                                              'S'
                                          ),
                                          array(
                                              '09:00:00',
                                              'Hull Middle School',
                                              'S',
                                              'V'
                                          ),
                                          array(
                                              '14:30:00',
                                              'Hull Middle School',
                                              'S',
                                              'W'
                                          )
                                      );
                                      function cmp($a, $b)
                                          {
                                              return strcmp($a[0], $b[0]);
                                          }
                                      
                                      
                                      echo "<pre>".print_r($theArray,1)."</pre>\n";
                                      usort(
                                          $theArray, "cmp");
                                      
                                      echo "<pre>".print_r($theArray,1)."</pre>\n";
                                        Write a Reply...