Page 1 of 1

Sorting multi-dimensional array by two values

Posted: Tue Oct 26, 2004 5:17 am
by primate
Hi,

I have a database with two tables. Each row in both tables has an associated time and date value entered in separate columns.

I run a SELECT query on the first table, then using php feed the values into a multi-dimensional array and check to see if a value exists in the each row of the result set from the first query. If it does I do a second SELECT query on the second table and overwrite the relevant entries from the first result set to leave me with one result set in a multi-dimensional array.

I need to reorganise the array by date and time so that the most recent result is the first result.

I've managed to do this by date OR time by using usort() and the following:

Code: Select all

<?php
function sortdates ($x, $y)    
	{ 
		if ( $x['Day'] == $y['Day'] )	
		return 0;	
			
		elseif ( $x['Day'] <$y['Day'] ) 
		return 1;	
		
		else 
		return -1;
	}

?>
However I can't get it to sort by both. I've tried nesting an 'if ' statement to attempt to only check if $x['Time'] /$y['Time'] is different if $x['Day']/ $y['Day'] is the same but to not avail.

The only way round it I can think of is by doing some kind of initial query, running through the results with php then doing a UNION query on both tables and letting SQL order them but this doesn't seem very efficient to me as I'd be having to get the result set from the first table twice.

Any suggestions?

Posted: Tue Oct 26, 2004 8:43 am
by hokiecsgrad
If you need to sort by date and then by time, then just concatenate the two fields in your "sortdates()" function. Like so:

Code: Select all

<?php
function sortdates ($x, $y)    
    &#123; 
        if ( $x&#1111;'Day'] . $x&#1111;'Time'] == $y&#1111;'Day'] . $y&#1111;'Time'] )    
        return 0;    
            
        elseif ( $x&#1111;'Day'] . $x&#1111;'Day'] <$y&#1111;'Day'] . $y&#1111;'Time'] ) 
        return 1;    
        
        else 
        return -1;
    &#125;

?>
Now, the manner in which you store your dates and times matters here, so I'm assuming that you're storing "day" as "yyyymmdd" and "time" as "hhmmss". If not, you'll need to rearrange them using the date() function provided by php. As an example of how this will work:
Unsorted:
20041025 031500 // Oct 25, 2004 at 3:15:00 AM
20041025 010500 // Oct 25, 2004 at 1:05:00 AM
20041031 000000 // Oct 31, 2004 at 12:00:00 AM
20041125 183000 // Nov 25, 2004 at 6:30:00 PM
20030101 000000 // Jan 1, 2003 at 12:00:00 AM

Sorted:
20030101 000000
20041025 010500
20041025 031500
20041031 000000
20041125 183000

Posted: Tue Oct 26, 2004 9:18 am
by primate
You truly are great, thankyou very much :)