|
Location: Web development - PHP License: The BSD License Sorting an array of PHP ObjectsPosted by Jason HouleNeed to sort an array of objects on a certain field? Use this class. |
Skill: IntermediatePosted: 02/01/2009Views: 729Rating: 5.00 /5Popularity: 2.39 |
| Sign Up to vote for this article |
I found the need to sort an array of objects on a given field. In this case it was a customers name. Rather than alter my customer class to allow for sorting or writing some code that wouldn't be reusable for anything else I decided to create this utility class to help with this situation if it were to be encountered with another collection of a different object.
First, here is the SortObjects class. As you can see, it is very simple.
The constructor for this class takes in the array you want to sort, the field you want to sort on, and an optional parameter to sort ascending 'ASC' or descending 'DESC' with the default being ascending.
The only other publicly accessible function is the getSortedArray() function which simply returns the sorted array. There really isn't any need to access any fields or the doSort() function directly.
The result would be:
This will obviously only work on PHP5 but we should all be using PHP5 by now anyway. If you need to alter this file for PHP4 the simply remove the private and public keywords as well as changing the function name "__construct" to "SortObjects"
I hope you all find this useful. I will definitely be making use of it.
This article, along with any associated source code and files, is licensed under The BSD License
| Jason Houle
| Location: |
Sign up to post message on the article message board!