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.
);
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.
// compare function function sortcompare($a, $b) { // include $sort_field variable global $sort_field; // time comparison if ( $timea ==$timeb ) { return 0; } return ($timea <p>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.</p>
0 comments:
Post a Comment