PHP: Sort an array of objects by an object property

I was asked if it was possible to re-order the list of friends when inviting people to events in the JomSocial v.1.8.3 community component of Joomla! 1.5

The problem here was that the array of friends is an array of objects, ordered by their database id as they were pulled from the database.I don’t want to be hacking the core functions that pulled the data from the database and re-ordering it there – I want to keep as close to the top layer as possible with simple bits of code, as I don’t want to waste time decoding other peoples work.

This all occurs in /components/com_community/views/events/view.html.php

If you know JomSocial, you might be aware that the friends model function ‘getFriends’ call looks like this:/components/com_community/models/friends.php

L.855

Well, that might suggest that we can order it by changing the call in view.html.php which currently is:

L.247

However swapping out ‘name’ for ‘username’ doesn’t work as rather than simply using this flag as the ORDER BY clause in the MySQL, the getFriends function uses a switch case to determine what action to take.models/friends.php

L.1030

Now I could just add a case for ‘username’ here. This would be the logical long term solution to any system over which I had real control. However, JomSocial is frequently updated, meaning any hacks I make must be reapplied, with no guarantee that they won’t have to be completely re-written. So this solution would mean changing two files, and getting deeper into the system. I want to keep my changes as few and as contiguous as possible.

Which brings me back to the original problem, and the ostensible perverse way of going about solving it.

So, I have an array of objects in the wrong order.What I’m going to do is loop through that single-dimension array, turning it into a two-dimensional array – one key the object (itself multi-dimensional), and the other key the username that we will sort on, obtained with the getDisplayName() method of the object.This new array will then be sorted with uname() and a simple custom function compare_uname($a, $b), and the sorted array looped to recreate the original single-dimensional array in the desired order.For JomSocial, this has been inserted in views/events/view.html.php at line 265

Leave a Reply

Your e-mail address will not be published. Required fields are marked *