Advertisement
VladimirsBudkins

Tree generator

Jan 16th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.30 KB | None | 0 0
  1. $result = $this->db->get('tbl_name')->result_array();
  2. $tree = getTree($result);
  3.  
  4. if (!function_exists('getTree')) {
  5.  
  6.     function getTree($array, $id_key = 'id', $parent_id_key = 'p_id', $weight_key = 'order') {
  7.         foreach ($array as $index => $element)
  8.             $array[$index]['children'] = getChildren($element[$id_key], $parent_id_key, $id_key, $weight_key, $array);
  9.         foreach ($array as $index => $element)
  10.             if ($element[$parent_id_key] > 0)
  11.                 unset($array[$index]);
  12.         return $array;
  13.     }
  14.  
  15. }
  16.  
  17. if (!function_exists('getChildren')) {
  18.  
  19.     function getChildren($parent_id_value, $parent_id_key, $id_key, $weight_key, $array) {
  20.         if (!is_array($array))
  21.             return false;
  22.         $children = array();
  23.         foreach ($array as $key => $item) {
  24.             if ($item[$parent_id_key] == $parent_id_value) {
  25.                 $weight = $item[$weight_key];
  26.                 while (isset($children[$weight]))
  27.                     $weight++;
  28.                 $children[$weight] = $item;
  29.             }
  30.         }
  31.         foreach ($children as $key => $child) {
  32.             $children[$key]['children'] = getChildren($child[$id_key], $parent_id_key, $id_key, $weight_key, $array);
  33.         }
  34.         ksort($children);
  35.         return $children;
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement