Tree Traversal Examples

	//取的某page的所有children, 並轉成簡單的陣列
	public static function get_children($page_id, $level=1, $stop_level=4, $labels=null, $app=false) {
		//避免最後一層還用API去抓資料,減少loading time
		if($level == $stop_level){
			return [];
		}

        $cql = 'parent=' . $page_id . ' order by title';
        $cql = urlencode($cql);
	    $URL = self::BASE_URL . 'content/search?cql=' . $cql . '&expand=body.view,metadata.labels';
        if($page_id == 10683286){
            //dd($URL);
        }

	    $data = self::curl($URL);
	    if($data == false){
	    	return [];
	    }
	    //dd($data);

	    $pages = $data->results;
	    if($pages == false){
	    	return [];
	    }

	    $children = [];
	    foreach ($pages as $key => $page) {
	    	if($labels != false){
	    		$item_labels = self::labels($page);
	    		//如果$is_app==true, 而且$os!='web', 則children裡面"沒有label android也沒有label ios"的項目也要抓出來
	    		//如果不是app, 就顯示全部
	    		if($app == true){
                    //如果完全沒有label就顯示
	    			if($item_labels != false){
	    				$match = self::match_labels($labels, $item_labels);
			    		if($match == false){
                            $m_android = self::match_labels(['android'], $item_labels);
                            $m_ios = self::match_labels(['ios'], $item_labels);
                            //要兩個都沒有才顯示
                            if($m_android == true || $m_ios == true){
			    			  continue;
                            }
			    		}
	    			}
	    		}
	    	}
	    	
	    	$item = [
	    		'id' => $page->id, 
	    		'title' => $page->title, 
	    		'content' => $page->body->view->value, 
	    		'children' => self::get_children($page->id, $level + 1, $stop_level, $labels, $app), 
	    		'level' => $level
	    	];

	    	$children[] = $item;
	    }

	    return $children;
    }

    public static function tree_traversal($nodes, $level=0){
    	foreach ($nodes as $key => $node) {
    		$node = Confluence::image_handler($node);
    		if($node['children'] != false){
                //$node['test'] = 'has children';
    			$node['children'] = self::tree_traversal($node['children'], $level+1);
    		}

    		$nodes[$key] = $node;
    	}

    	return $nodes;
    }

    public static function tree_menu($nodes, &$html){
    	if($nodes == false){
    		return;
    	}

    	$html .= '<ul>';
    	foreach ($nodes as $key => $node) {
    		if($node['children'] == false){
    			$html .= '<li>';
    			$html .= '<a href="#" data-tab="#tab_' . $node['id'] . '">' . $node['title'] . '</a>';
    			$html .= '</li>';
    		}else{
    			$html .= '<li>';
	    		$html .= '<a href="#">' . $node['title'] . '</a>';
	    		self::tree_menu($node['children'], $html);
	    		$html .= '</li>';
    		}
    	}

    	$html .= '</ul>';
    }