So, you have an array in PHP which is made up of multiple fields and you want to sort by multiple fields. How to do it?

Function 'array_multisort' to the rescue

Well for me the easiest way to do this was using the PHP array_multisort function which gives the ability to sort by multiple keys.

The function signature is: array_multisort( &$arr1[, sort type [, &$arr2...]]) and it returns true if successful. 

So what does it do?

Well I found the explanation on quite confusing, but essentially what it does is apply sorting rules (left-to-right) on all the array arguments supplied.

The sort parameters are a combination of SORT_ASC (the default), SORT_DESC, plus a whole host of other sort options (numeric comparison etc); and the arrays are passed by reference and each ends up sorted in relation to the previous.

Example Code

Now this is best demonstrated by an example, so suppose you had a payroll array containing name, dob, salary and ni_number and you wanted to sort the array by salary and dob...

	// populate payroll array
	$payroll = array();
	$payroll[] = array( 'name' => 'Gary',   'dob' => '1970/01/31', 'salary' => 25000, 'nino' => 'ABC-1' );
	$payroll[] = array( 'name' => 'Dennis', 'dob' => '1960/09/15', 'salary' => 30000, 'nino' => 'XYZ-123' );
        $payroll[] = array( 'name' => 'Bill',   'dob' => '1972/05/22', 'salary' => 25000, 'nino' => '1234-XY1' );
	// want to sort by salary and dob - so need arrays for the 'keys' we want to sort by
        $sal = array();
        $dob = array();
	for ($i = 0; $i < count($payroll); $i++) {
	  $sal[] = $payroll[$i]['salary'];
	  $dob[] = $payroll[$i]['dob'];  // dont need to reverse dob coz already in YYYY/MM/DD format
	// now apply sort
	array_multisort($sal, SORT_ASC, SORT_NUMERIC, 
			$dob, SORT_ASC,
	// sorted results will be in $payroll now in salary+dob order!!

So then doing a var_dump on $payroll reveals the order to now be:

	$payroll[0] = array( 'name' => 'Gary',   'dob' => '1970/01/31', 'salary' => 25000, 'nino' => 'ABC-1' );
        $payroll[1] = array( 'name' => 'Bill',   'dob' => '1972/05/22', 'salary' => 25000, 'nino' => '1234-XY1' );
	$payroll[2] = array( 'name' => 'Dennis', 'dob' => '1960/09/15', 'salary' => 30000, 'nino' => 'XYZ-123' );
As you can see the array is sorted by salary and dob (notice the use of multiple sort parameters against the salary element - sort ascending & numeric).

Try it yourself

If you want to try it yourself simply copy and paste the above code (add in some extra payroll examples), put it in its own PHP page on your local server and stick some var_dump or print_r debug statements in the code so you can see what its doing.