Scripts

PHP Array Tree

Als je een pagina systeem wilt maken met oneindig veel subpagina's, kan deze class je van pas komen. Ik maak er expres eerst een Array van, en dan pas een table. Je zou ook al veel eerder er meteen een table, ul/li list van kunnen maken, zoals hier. Het nadeel hiervan is is echter dat je telkens een hele nieuwe class moet maken als je een keer andere html van wilt maken. Met deze array kan je met een simpele class, bijvoorbeeld die ik als voorbeeld helemaal onderaan geef, de array uitlezen. Ook kan je deze array bijvoorbeeld gebruiken als je Smarty gebruikt ( http://smarty.incutio.com/?page=SmartyDocsErrorsAndSuggestions ctrl+f -> tree ) Dit is een voorbeeld van een SQL tabel: CREATE TABLE paginas ( id int(10) auto_increment, titel varchar(255), menuid int(10), parent int(10), PRIMARY KEY (id) ); Veel succes ermee. ps. http://youmuppet.com/mootree/ dit kan je goed in combinatie met deze class gebruiken.

php-array-tree
arrayTree.php
<?php

class Tree { 

  /** 
  * @desc array with elements 
  * @type array 
  * @access private 
  **/ 
  var $aElements; 

  /** 
  * @desc backbone array 
  * @type array 
  * @access private 
  **/ 
  var $result; 
  
  /**
   * Register the levels, to calculate the max level for example
   *
   * @var array
   */
  
  var $levels;  
  
  /**
   * The elements ordered by level
   *
   * @type array
   */
  
  var $lElements;
  
  
	/** 
	* @desc constructor method 
	* @param 
	* @access public 
	* @return void 
	**/
	function Tree(){ 
		$this->aElements  = array(); 
		$this->lElements  = array(); 
		$this->result     = array(); 
		$this->levels 	  = array();
	} 

	/**
	 * Add an element to the array
	 *
	 * @param numeric $iId (The id of the element)
	 * @param array $properties	(All kind of extra properties)
	 * @param numeric $iParentId (The parent id)
	**/


	function addNode($iId, $properties, $iParentId = 0){ 
		$this->aElements[$iId] = array('properties' => $properties, 'parent' => $iParentId); 
	} 

	/**
	 * Gets the parens ids
	 *
	 * @param string/numeric $iId
	**/
	
	function getParents($iId){
		$dad = $this->aElements[$iId]['parent'];
		$parent[] = $dad;
		while($dad){
			if($dad = $this->getParent($dad)){
				$parent[] = $dad;
			}			
		}
		$this->aElements[$iId]['parents'] = $parent;
		return $parent;
	}

	/**
	 * Get the parent ID
	 *
	 * @param string/numeric $iId
	 * @return The parent ID or false
	**/
	
	function getParent($iId){
		if(!empty($this->aElements[$iId]['parent'])){
			return $this->aElements[$iId]['parent'];
		}else{
			return false;
		}
	}
	
	/**
	 * Counts the level depth
	 *
	 * @param string/numeric $iId
	 * @return numeric 
	**/
	
	function level($iId){
		$level = count($this->getParents($iId));
		$this->aElements[$iId]['level'] = $level;
		$this->levels[$iId] = $level;
		if(!$this->getParent($iId)){
			$this->lElements[1][$iId] = $this->aElements[$iId];
		}else{
			$this->lElements[$level+1][$iId] = $this->aElements[$iId];
		}
		return $level;
	}
	
	/**
	 * Returns the max level.
	 *
	 * @return number with the max level depth
	**/
	
	function maxLevel(){
		$max = 0;
		foreach($this->levels as $level){
			if($level > $max){
				$max = $level;
			}
		}
		return ($max+1);
	}
	
	/**
	 * Generates the tree Array
	 *
	 * @return array (within the tree array)
	 */
	
	function getArray() { 

		foreach($this->aElements as $iId => $element){
			$this->level($iId);
		}
		
		foreach($this->lElements[1] as $id => $element){
			$this->result[$id] = '';
		}
		
		for($i=$this->maxLevel();$i>=1;$i--){
			if(isset($this->lElements[$i]) and is_array($this->lElements)){
				foreach($this->lElements[$i] as $id => $element){
					$parent = $this->getParent($id);
					if($parent != 0){
						// Als de dochter een parent heeft
						$this->result[$id]['properties'] = $this->aElements[$id]['properties'];
						if(!isset($this->result[$id])){					
							// Als de pagina nog niet bestond
							$this->result[$parent]['childs'][$id]['properties'] = $element['properties'];
						}else{
							// De pagina bestond dus wel al
							$this->result[$parent]['childs'][$id] = $this->result[$id];
						}
						// Overige verwijderen
						unset($this->result[$id]);
					}else{
						$this->result[$id]['properties'] = $this->aElements[$id]['properties'];
					}
				}
			}
		}
		return $this->result; 
	}
	
	function getLElements(){
		return $this->lElements;
	}
}

?>


example.php

<?php

include('arrayTree.php');

$tree = new Tree();
$sql = "SELECT id,titel,parent,menuid FROM paginas ORDER BY menuid";
$res = mysql_query($sql);
while($page = mysql_fetch_assoc($res)){
	$tree->addNode($page['id'],$page,$page['parent']);
}
$paginas = $tree->getArray();

echo '<pre>';
print_r($paginas);
echo '</pre>';

?>

Ik heb ook een voorbeeld class gemaakt waarmee je deze array kunt uitlezen

readTreeArray.php
<?php
	class printArrayTree {
		
		var $buffer;
		var $array;		
		
		function printArrayTree(){
			$this->array = array();
			$this->buffer = '';
		}		
		
		function make_row($array,$level=0){
			foreach($array as $element){			
				$this->buffer .= '<tr><td>'.$element['properties']['id'].'</td>
						<td style="padding-left: '.(15*$level).'px;">'.($level != 0 ? '&rsaquo; ' : '').' '.$element['properties']['titel'].'</td>
					</tr>';

				if(isset($element['childs']) and is_array($element['childs'])){
					$this->make_row($element['childs'],($level+1));				
				}
			}		
		}
				
		function print_table(){
			return '<table width="50%" cellspacing="0">
				<tr>
				<th>ID</th>
				<th>Pagina naam</th>
			</tr>'.$this->buffer.'</table>';
		}
		
	}
?>


En deze gebruik je uiteindelijk dan zo:

<?php

include('arrayTree.php');

$tree = new Tree();
$sql = "SELECT id,titel,parent,menuid FROM paginas ORDER BY menuid";
$res = mysql_query($sql);
while($page = mysql_fetch_assoc($res)){
	$tree->addNode($page['id'],$page,$page['parent']);
}
$paginas = $tree->getArray();

echo '<pre>';
print_r($paginas);
echo '</pre>';

include('readTreeArray.php');

if(count($paginas) >= 1){		
	$table = new printArrayTree;
	$table->make_row($paginas);
	echo $table->print_table();		
}


?>

Reacties

0
Nog geen reacties.