应该除去返回所有上级节点的节点,否则会出现死循环。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>";
{
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>";
解决方案 »
- 对于Get 得到的String数据要进行怎样的预处理才安全
- private和protected
- SqlServer有点怪:php用mssql连sqlserver,select id from table,可以得到结果,select * 和select `id` 或select id, title都得不到结
- php如何加密文件?
- 新年继续发问,关于pear的使用
- [求助]请问如何使用PHP取得毫秒级的系统时间?
- 在页面中操作一个列表框的时候如何获得另一个列表框当前的值?
- 请问为什么上传路径有误??解决后立即结帖
- php设置问题
- 难道整个论坛里就没有一个人能解决我这个问题,问了几遍没人回答?
- 复制文件夹下所有文件php程序怎么实现
- 如何判断字符是整数
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));