intelliproject logo

Location: Web development - PHP    License: The BSD License

Sorting an array of PHP Objects

Posted by Jason Houle

Need to sort an array of objects on a certain field? Use this class.

Skill: Intermediate

Posted: 02/01/2009

Views: 729

Rating: 5.00 /5

Popularity: 2.39

Sign Up to vote for this article

Introduction

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.

The code

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.

Example

The result would be:

Points of Interest

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"

Conclusion

I hope you all find this useful. I will definitely be making use of it.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the author

Jason Houle

Location: United States
Ocupation: Java and PHP Developer
Home page: http://jasonhoule.com

Posted by pepelea romeo sorin at 26/12/2010 12:26
what is the execution time for this . is it reliable for implementing in production for large dataset app?

Sign up to post message on the article message board!