I have a typical nested tree model and I want to build an array with a 'children' array based on the levels or depths, but it doesn't seem to be working for me. Here's what I have now:
while($this->tax->getTreeNext($nodes))
{
$level = $this->tax->getTreeLevel($nodes);
if($level != 0){
echo $level . '-' . $current_level;
if($level > $current_level){
$terms[$i] = array(
'term_id' => $terms[$i-1]['term_id'],
'name' => $terms[$i-1]['name'],
'level' => $terms[$i-1]['level'],
'children' => array(
'term_id' => $nodes['row']['term_id'],
'name' => $nodes['row']['name'],
'level' => $level,
)
);
unset($terms[$i-1]);
}else{
$terms[$i] = array(
'term_id' => $nodes['row']['term_id'],
'name' => $nodes['row']['name'],
'level' => $level
);
}
$current_level = $level;
$i++;
}
}
This works for a single child, but not if the children have children... any suggestions how to fix this?
Thank you!
Edit:
This is the latest that appears to be close to working:
function process(&$arr, &$prev_sub = null, $cur_depth = 1) {
$cur_sub = array();
while($line = current($arr)){
if($line['depth'] < $cur_depth){
return $cur_sub;
}elseif($line['depth'] > $cur_depth){
$prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );
}else{
$cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
$prev_sub =& $cur_sub[$line['term_id']];
next($arr);
}
}
return $cur_sub;
}
The tree is passed into this with depth values associated to each node. The current problem is with the elseif($line['depth'] > $cur_depth)
. If a node has children, it only returns arrays for the children, but it does not include that nodes name or term_id.
Thank you!