doukan6564 2012-07-27 08:13
浏览 49
已采纳

如何在PHP中实现多线程递归?

I have a category tree in XML like

<cat name='cat_1' id='1'>

 <cat name='cat_2' id='2'>
   <cat name='cat_3' id='3'>

   </cat>
 </cat>

 <cat name='cat_4' id='4'>
   <cat name='cat_5' id='5'>

      <cat name='cat_6' id='6'>
        <cat name='cat_7' id='7'>

        </cat>
      </cat>
  </cat>  
 </cat>

</cat>

now I want to implement code such that I can travers this tree an find categories ids by the name i.e. If input is cat_6 than result should be 6;

What I have done

$xmlCatTree // is my simple xml object

class MyClass{   
 public function traverseForId($cat_name , $xmlCatTree )
      {

        if($xmlCatTree->attributes()->name == $cate_name)
            {
              return $xmlCatTree->attributes()->id;
            }
        if(count($item->children())>0){
        foreach($item->children() as $child)
        {
             return $this->traverseForId($cat_name,$child);
        } } 

      } 

}

It works perfectly for single branch i.e child nodes of cat_2 will have correct results but if I search for cat_7 nothing will return. I thing It happens due to branched recursion. I want to know how to cop this.

  • 写回答

2条回答 默认 最新

  • doujiao8649 2012-07-27 08:19
    关注

    It seems, that you are using SimpleXML, thus I recommend to directly query the tree.

    foreach ($xmlCatTree->xpath('//cat[@name=' . $cat_name . ']') as $node)
      return $node->attributes()->id;
    }
    return null;
    

    This is even more elegant, because it directly reflects, what you are trying to achieve: Give me all the nodes with attribute "name" with the value "$cat_name".

    Or (because it seems, that the ID is already part of the category name ;))

    list($unusedThingy, $id) = array_pad(explode('_', $cat_name, 2), 2, null);
    return $id;
    

    But I guess thats not really, what you are looking for ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等