Sort Multidimensional Array in PHP

Sort Multidimensional Array in PHP

Need Some Help? We are here for you!

We have a very friendly service - Come and chat to us and let us know what you need, we work for an hourly fee and can also provide you a no obligation quote and begin work immediately in most cases. Click "Request Support" or use our Live Chat.

Request Support
There is a mobile optimized version of this page, view AMP Version.

A common problem people face whilst coding with PHP is sorting Multidimensional arrays. Sorting an array with one level to is quite a simple task, however, sorting arrays that consist of many levels can be quite a challenge for some new developers. Here is one way in which we can make this daunting task seem a lot simpler. One short sorting function is all that is needed. It really couldnt be simpler to sort multidimensional arrays in PHP!

<?php
function aasort (&$array, $key) {
	$sorter=array();
	$ret=array();
	reset($array);
	
	foreach ($array as $ii => $va) {
		$sorter[$ii]=$va[$key];
	}
	asort($sorter);
	
	foreach ($sorter as $ii => $va) {
		$ret[$ii]=$array[$ii];
	}
	$array=$ret;
}
?>

The above function works really well and is also relatively quick at doing the sort. Here we’ll see an array get sorted using this function.

Array (
	[0] => Array
	(
		[Name] => Ben
		[Surname] => Saunders
	)
	[1] => Array
	(
		[Name] => Bob
		[Surname] => Ericsson
	)
	[2] => Array
	(
		[Name] => Allen
		[Surname] => Jones
	)
	[3] => Array
	(
		[Name] => Dean
		[Surname] => Williams
	)
	[4] => Array
	(
		[Name] => Josh
		[Surname] => Burley
	)
)

To sort the array by ‘Surname’ We do the following

<?php 
    aasort($your_array,"Surname");
?>

And the output

Array(
	[4] => Array
	(
		[Name] => Josh
		[Surname] => Burley
	)
	[1] => Array
	(
		[Name] => Bob
		[Surname] => Ericsson
	)
	[2] => Array
	(
		[Name] => Allen
		[Surname] => Jones
	)
	[0] => Array
	(
		[Name] => Ben
		[Surname] => Saunders
	)
	[3] => Array
	(
		[Name] => Dean
		[Surname] => Williams
	)
)

There you go, the struggles of sorting multidimensional arrays can be put behind you.

Need Some Help? We are here for you!

We have a very friendly service - Come and chat to us and let us know what you need, we work for an hourly fee and can also provide you a no obligation quote and begin work immediately in most cases. Click "Request Support" or use our Live Chat.

Request Support

Author: Josh Burley

Over 10 years software and website development, more recently moving into app development. Became a founding member and managing partner of WebDesires in late 2014 early 2015. Now dedicate most of my time to the company and helping us grow into the industry.