Sorting A Multidimensional Array With PHP

Monday, June 9, 2008 - 09:51

Sorting an array is easy in PHP thanks for the built in sorting functions. However, when it comes to sorting a multidimensional array you need to employ these functions in a certain way, especially if you want to vary the data item you want to sort by.

Take the following defined array, taken from the top news stories in the Science and Nature section of the BBC website.

1
2
3
4
5
6
$bbcNews = array(
 array('Martian soil frustrates Phoenix','7442233','Science/Nature','Saturday, 7 June 2008 00:25'),
 array('Natural lab shows sea\'s acid path','7437862','Science/Nature','Sunday, 8 June 2008 18:08'),
 array('Hints of "time before Big Bang"','7440217','Science/Nature',' Friday, 6 June 2008 15:43'),
 array('Bacteria could stop frog killer','7438205','Science/Nature','Friday, 6 June 2008 08:46')
);

In order to sort the array by any item I will use the PHP function usort(). This function takes two parameters, the first is the array that is to be sorted and the second is a string which will be used as a callback function to allow comparison between one item and the next. All of the sorting intricacies are sorted out behind the scenes, all you have to do is get this comparison function to return a 0 when the two values are the same, a negative number if the first is less and the second and a positive value when the first is greater than the second. The following bit of code will run the sort function on the array, it doesn't have a return value as the array itself is sorted.

usort($bbcNews, 'sortcompare');

Before we define the sortcompare() function we will use a variable to store the item of the array that we wish to sort by. This variable is called $sort_field.

$sort_field = 1; // enter the number of field to sort

In order to use this variable we will include it in the scope of the function using the global command. At the moment this will cause the function to sort by the ID number of the news article (the second item in the array). Just change this to whatever array item that you want to sort by. Remember that, as will all PHP arrays (unless you set otherwise), this number starts from zero.

Here is the callback function that is used to sort the array. It is split into three parts. First it tries to convert the string into a date, if this is successful it returns a comparison value based on the previously mentioned negative, zero and positive values. If both the values can't be converted into dates it check to see if they are numeric. If neither of these two situations are true then the PHP function strcasecmp() is run on the two strings. This is a binary safe case-insensitive string comparison function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// compare function
function sortcompare($a, $b)
{
 // include $sort_field variable
 global $sort_field;
 if ( ($timea = strtotime($a[$sort_field])) !== false && ($timeb = strtotime($b[$sort_field]))!==false ) {
  // time comparison
  if ( $timea ==$timeb ) {
   return 0;
  }
  return ($timea < $timeb) ? -1 : 1;
 } elseif ( is_numeric($a[$sort_field]) && is_numeric($b[$sort_field]) ) {
  // numeric sort
  if($a[$sort_field] ==$b[$sort_field]){
   return 0;
  }
  return ($a[$sort_field] < $b[$sort_field]) ? -1 : 1;
 } else {
  // normal case insensitive string comparison
  return strcasecmp($a[$sort_field], $b[$sort_field]);
 }
}

To print out the output of this function use the following bit of code. This will verify that the function works by printing out the array in full.

echo '<pre>'.print_r($bbcNews,true).'';
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment