I think you may be underestimating the capabilities of SQL, though I'm not claiming it would necessarily be simple or easy, mind you. But if you're more comfortable with a PHP solution, you can certainly pursue one using [man]usort/man, for instance. All(?) you need is a callback function that will take as its two parameters two top-level entries from your array. It would then need to walk through your desired sorting logic and ultimately return "...an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second."