Hey guys, I ran into a bit of a problem and have been trying to solve it for over two weeks. 5 failed attempts later, I've decided to throw in the towel and ask for advice.

OK, here goes:

I'm building an application that uses business objects. The objects are in a heirarchy, so there can be a parent object with X amount of children objects.

Everything was going great until I tried to implement functionality to sort results as I spilled them to the page. The problem: PHP's sort() function doesn't sort objects, and becuase of how the database is designed, there's no way to have mysql sort during the query.

My approach was to extract the sort-values from the objects and stuff them as strings into an array. If it was a parent object, it would store the parent's ID, and if it was a child object, it would look up it's parent id and store that (all the values were stored on the same row for matching id's). So, let's say I had 1 parent and 1 child, and I was going to sort by 1 value for each one, I would end up with an array like this-

$SortArray = array(
    0 => array(
        ParentValue => "abc",
        ChildValue => "abc",
        ParentID => 15),
    1 => array(
        ParentValue => "abc",
        ChildValue => "abc",
        ParentID => 4),
    2 => array(
        ParentValue => "abc",
        ChildValue => "abc",
        ParentID => 37),

... and so on

I got that to work, mostly. I ran into a problem of not being able to get php to order the columsn in the array how I wanted. Since sort() sorts from the left most column to the right, this was definitly a problem. I found a work-around but I suspect it's one of thoes things I'll look back on in a few years and wonder how anyone could have writen something like that. It took nearly 300 lines of code :bemused:. I'm sure there has to be a better way of doing this, and any advice would be appreciated.

Summary: what I need to be able to do is sort an array of parent objects by their value(s) or their children(s) values. Since the child always attaches to the parent, they don't need to be sorted.

    I browsed over all the different sort functions and didn't find one that would work. I did however finally find a solution.

      Write a Reply...