Added sort option for array collection #213

wants to merge 2 commits into


None yet
5 participants

I have added a sorter class and sortBy method for the ArrayCollection class. It gives the option to reorder the ArrayCollection after someone has gotten it from the database, e.g. from a relationship. It takes an array of method names to sort by in order to priority and it takes an optional boolean to set the order to ascending. Here is an example:

$arraycollection->sortBy(array('getName()', 'getAddress()'));

It will recursively loop the collection change the order. Each time it will look to see if the previous matching option is the same as for the previous element and then store those elements in list to be reordered.

Once it has looped all the elements it will reorder the elements it has matched and if there is another option to reorder by it will loop only the elements it matched last time so it is not looping the whole array each time.


thank you for positing this Pull Request. I have automatically opened an issue on our Jira Bug Tracker for you with the details of this Pull-Request. See the Link:


Ocramius commented Nov 11, 2012

@andrewtarry are you sure this wouldn't work by re-using the matching API internally?

@stof stof commented on the diff Nov 21, 2012

@@ -2,3 +2,5 @@ build/

stof Nov 21, 2012


Please remove this. Files specific to your IDE should be ignored locally. See for help

@stof stof commented on the diff Nov 21, 2012

@@ -496,5 +496,17 @@ public function matching(Criteria $criteria)
return new static($filtered);
+ /**
+ * Reorder the elements by a series of methods to reorganise the elements.
+ *
+ * @param array $sortBy An array of method names to regoraise by.
+ * @param boolean $ascend [Optional] True if the order should be ascending
+ */
+ public function sort(array $sortBy, $ascend = false)

stof Nov 21, 2012


Adding the method in the class without adding it in the interface is useless (you cannot ensure you will receive an ArrayCollection each time). And adding it in the interface is impossible as it would be a BC break


beberlei commented Jan 10, 2013

This cannot work, as everything on ArrayCollection has to be on the Collections interface and extending that is not possible because of BC. Also the automatic sorting is way to performance intensive.

You should build yourself a helper object that allows sorting of collections, we cannot add this sort of code, sorry :-(

beberlei closed this Jan 10, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment