How to Sort Multidimensional Array Using Usort() and Uasort() Function in PHP

Multidimensional Arrays are very powerful and flexible. They are widely used in PHP programming. Sorting arrays is easy, using the sort() and ksort() but these functions only work on one dimensional array. For multidimensional arrays we need to define our own functions along with PHP functions to sort arrays.

Lets begin with the code for that.

$array = [
	[
		'month' => 10,
		'sales' => [
			'trousers' => 100,
			'shirt' => 103,
			'shorts' => 40,
			],
	],
	[
		'month' => 12,
		'sales' => [
			'trousers' => 140,
			'shirt' => 134,
			'shorts' => 45,
		],
	],
	[
		'month' => 3,
		'sales' => [
			'trousers' => 110,
			'shirt' => 104,
			'shorts' => 89,
		],
	],
];

Here is this code that shows an example of multidimensional array. It has sales record of 3 months of a garment store. We need to sort this data on the basis of a month which is obviously one key of inner array. Now in order to do so we need to first define a simple PHP function like this.

function asc_number_sort( $x, $y ) {
	if ( $x['month'] > $y['month'] ) {
		return true;
	}
	else if( $x['month'] < $y['month'] ){
		return false;
	}
	else{
		return 0;
	}
}

Now we will use usort() function to actually sort our array.

usort( $array, 'asc_number_sort' );

Now if you will print the array you will see this output.

Now lets try alphabetical sorting. Here we have an array of students’ names and marks they obtained.

$students = [
	['name' => 'Richard', 'marks' => 110],
	['name' => 'Adams', 'marks' => 110],
	['name' => 'Gordon', 'marks' => 124],
	['name' => 'Cindy', 'marks' => 144]
];

We want to sort this array on the basis of students’ names. So, here is our PHP function to sort.

function string_sort( $x, $y ) {
	return strcasecmp( $x['name'], $y['name'] );
}

Now we need to use usort() with our PHP function.

usort( $students, 'string_sort' );

Here is the output if you will print the students array.

Now lets suppose Students array has keys of its own in some order. Like here is the array.

$students = [
	120 => [ 'name' => 'Richard', 'marks' => 110 ],
	43 => [ 'name' => 'Adams', 'marks' => 110 ],
	56 => [ 'name' => 'Gordon', 'marks' => 124 ],
	57 => [ 'name' => 'Cindy', 'marks' => 144 ]
];

Now usort() will sort array but we will lose keys of array. In order to preserve keys we need to use uasort() function.

uasort( $students, 'string_sort' );

Here is the output.

So when we work with multidimensional arrays we must try to use uasort() function.