应该除去返回所有上级节点的节点,否则会出现死循环。function getBranch($node,$depth=1)
{
global $allnode,$flow_branch,$branch;

//当前节点分支数
$sub_branch = 0;
for ($i=0;$i<count($allnode);$i++)
{ $v = $allnode[$i];
if ($node == $v['from'])
{
//分支不存在时,初始化该分支数组
if (!isset($flow_branch[$branch]))
{
$flow_branch[$branch] = array();
//初始化根结点
array_push($flow_branch[$branch], $node);
}
//当前节点有2个以上的子结点时,要添加新的分支。
if ($sub_branch > 0)
{
$branch++;
//新分支与上一分支在当前深度以上,节点是相同的
$flow_branch[$branch] = array_slice($flow_branch[$branch-1],0,$depth);
}
//下一节点不在当前分支时,才将节点存入分支数组
if (!in_array($v['to'],$flow_branch[$branch]))
{

array_push($flow_branch[$branch], $v['to']);
//当前节点的子节点数+1
$sub_branch++;
//寻找下一节点的子节点,深度+1
getBranch($v['to'],$depth+1);
}
}
}
}$flow_branch = array(); //分支数组
$branch=0; //分支数
$start_node=3349; //起点
getBranch($start_node);
echo "<pre>";
print_r($flow_branch);
echo "</pre>";

解决方案 »

  1.   

    不过是个图的遍历问题function branch($from, &$nodes, $flow=array()) {
    static $ret;
    if(empty($flow)) $ret = array();
    if(in_array($from, $flow)) {
    $flow[] = -$from; //有环路
    $ret[] = $flow;
    return;
    }
    $flow[] = $from;
    $t = array_filter($nodes, create_function('$v', "return \$v['from'] == $from;"));
    if($t) {
    foreach($t as $v) {
    branch($v['to'], $nodes, $flow);
    }
    }else {
    $ret[] = $flow;
    // return;
    }
    return $ret;
    }print_r(branch(3349, $allnode));