You have multiple options to speed it up:
- Select all rows from table and do the recursion only on the PHP side. It's only an option if there are not too many rows in table.
- You can self join the table. This is a nice option if you know that there are no more levels of hierarchy in the future. Look at the post: http://blog.richardknop.com/2009/05/adjacency-list-model/
- Use nested sets: http://en.wikipedia.org/wiki/Nested_set_model
- Or my favorite: Closure Table
- Use some kind of caching. You could cache the db queries or the whole tree menu html or the PHP array for example.
Caching example:
Caching you can do in normal files or use specialized api's like memcache, memcached or apc. Usually you have a class with 3 basic methods. An interface could look like:
interface ICache
{
public function get($key);
public function set($key, $value, $lifetime = false);
public function delete($key);
}
You can use it like:
public function getHierarchy($id)
{
$cached = $this->cache->get($id);
if (false !== $cached) {
return $cached;
}
// run another method where you build the tree ($arr)
$this->cache->set($id, $arr, 3600);
return $arr;
}
In the example the tree will be cached for one hour. You also could set unlimited lifetime and delete the key if you insert another item to the db.