<?php
$rows = array( 0=>array('category_id'=>1,'parent_id' =>3,'category_name' =>'Second Child','category_position'=>2),
1=>array('category_id' =>2,'parent_id' =>0,'category_name' =>'Second Parent','category_position'=>2),
2=>array('category_id' =>3,'parent_id' =>0,'category_name' =>'First Parent','category_position'=>1),
3=>array('category_id' =>4,'parent_id' =>0,'category_name' =>'Third Parent','category_position'=>3),
4=>array('category_id' =>5,'parent_id' =>3,'category_name' =>'First Child','category_position'=>1),
5=>array('category_id' =>6,'parent_id' =>5,'category_name'=>'Second Sub-Child','category_position'=>2),
6=>array('category_id' =>7,'parent_id' =>5,'category_name' =>'First Sub-Child','category_position'=>1)
);
$ordered = chain('category_id', 'parent_id', 'category_position', $rows);
foreach($ordered as $item)
{
echo str_repeat('------', $item['indent']).$item['category_name'].'<br>';
}
function chain($primary_field, $parent_field, $sort_field, $rows, $root_id=0, $maxlevel=25)
{
$c = new chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel);
return $c->chain_table;
}
class chain
{
var $table;
var $rows;
var $chain_table;
var $primary_field;
var $parent_field;
var $sort_field;
function chain($primary_field, $parent_field, $sort_field, $rows, $root_id, $maxlevel)
{
$this->rows = $rows;
$this->primary_field = $primary_field;
$this->parent_field = $parent_field;
$this->sort_field = $sort_field;
$this->buildChain($root_id,$maxlevel);
}
function buildChain($rootcatid,$maxlevel)
{
foreach($this->rows as $row)
{
$this->table[$row[$this->parent_field]][ $row[$this->primary_field]] = $row;
}
$this->makeBranch($rootcatid,0,$maxlevel);
}
function makeBranch($parent_id,$level,$maxlevel)
{
$rows=$this->table[$parent_id];
foreach($rows as $key=>$value)
{
$rows[$key]['key'] = $this->sort_field;
}
usort($rows,'chainCMP');
foreach($rows as $item)
{
$item['indent'] = $level;
$this->chain_table[] = $item;
if((isset($this->table[$item[$this->primary_field]])) && (($maxlevel>$level+1) || ($maxlevel==0)))
{
$this->makeBranch($item[$this->primary_field], $level+1, $maxlevel);
}
}
}
}
function chainCMP($a,$b)
{
if($a[$a['key']] == $b[$b['key']])
{
return 0;
}
return($a[$a['key']]<$b[$b['key']])?-1:1;
}
?>