Location: PHPKode > scripts > Recursion Helper > RecursionHelper.php
<?php
  
/**
* @author Thomas Schäfer
*/
class RecursionHelper
{
  public $idField      = "Id";
  public $parentField  = "ParentId";
  public $weightField  = false;
  public $newWeightField  = false;
  public $childField   = "children";

  public $referenceKey   = null;
  public $referenceValue = null;
  
  private $tree = array();
  private $flat = array();
  
  public function __construct(array $data)
  {
    $this->flat = $data;
  }
  
  public function getTree()
  {
    return $this->tree;
  }
  
  public function getFlat()
  {
    return $this->flat;
  }
  
  public function init()
  {
    $this->toTree();
    return $this;
  }
  
  private function toTree()
  {
    $indexed = array();
    $flat = $this->flat;
    $idField      = $this->idField;
    $parentField  = $this->parentField;
    $childField   = $this->childField;
    
    $root = null;
    $__root = null;
    $return = array();
    
    foreach ($flat as $row)
    {
      if($this->referenceKey and $this->referenceValue){
        $row[$this->referenceKey] = $this->referenceValue;
      }
      $indexed[$row[$idField]] = $row;
      $return["flat"][$row[$idField]] = $row;
    }
    unset($flat);
    
    $i=0;    
    foreach ($indexed as $key => $row)
    {
      if(!$__root)  
        $__root = $row[$parentField];
      if(!empty($this->newWeightField) and array_key_exists($this->newWeightField, $indexed[$key]))
      {
        $indexed[$key][$this->newWeightField] = $i;
        $return["flat"][$key][$this->newWeightField] = $i;
      }
      $indexed[$row[$parentField]][$childField][$key] =& $indexed[$key];
      $i++;
    }
    $this->tree = $indexed[$__root][$this->childField];
    unset($indexed);
    $this->flat = $return["flat"];
    unset($return);
  }
  
}
Return current item: Recursion Helper