Here's how I'm getting my data from database. It is a 3 level hierarchy. Parent, child and children of child.
page_id | parent_id
1 0
2 1
3 0
4 3
The top data shows 0 as the parent.
$id = 0;
public function getHierarchy($id)
{
$Pages = new Pages();
$arr = array();
$result = $Pages->getParent($id);
foreach($result as $p){
$arr[] = array(
'title' => $p['title'],
'children' => $this->getHierarchy($p['page_id']),
);
}
return $arr;
}
So far I'm getting data but it's kinda slow. The browser loads so long before showing the data. How can I make my code faster so it does not take long for the browser to load data?
Thanks.
You have multiple options to speed it up:
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.