首页 > 解决方案 > 如何在php中解析层次结构函数

问题描述

我有一种情况,我在函数中收到了一个 ID。当我将这个 ID 传递给 API 时,它会为我提供一个关系列表,例如,如果我作为 ID A 传递,我会得到:

类型
一个 关系类型 1
一个 C 关系类型2
C D 关系类型3
D 一个 关系类型4

现在我需要以递归方式找到我获得的所有唯一 ID (A,B,C,D) 的关系,并且对于每个我需要列出具有类型的 ID,直到我找不到更多的关系。

最后,我需要将所有这些数据保存在数据库中,这不是问题,但它将是 From、To 和 Type 的组合。

这是在 php 中尝试的,我正在使用一个类作为开始的基础,从而实现 DFS 来做 . 是否有更好的替代方案,可以有效调用 API 并加快处理速度。

谢谢你的帮助。

标签: phpdepth-first-search

解决方案


简单的递归。像这样的东西

基本的

class Relations {

   public static function getLinksFromDB(relation_id){
      return $db->array(); // return an array of matches based on the passed in $relation_id from the database, using your normal query here.
   }
   public static function getLinks(relation_id){
       $ret = [];
       $r_ids = Relations::getLinksFromDB(r_id); // when this returns nothing, you will have reached the end of your links, with an exception, if you have any amount which is self contained like A->B, B->C and C->A, then you will have an infinite loop. this could be solved by passing in a counter and once it reaches the counter of depth, just return.
       foreach($r_ids as $r_id){
           $ret[] = Relations::getLinks($r_id);
       }
       return $ret;
   }
}

带深度限制器

class Relations {

   public static function getLinksFromDB(relation_id){
      return $db->array(); // return an array of matches based on the passed in $relation_id from the database, using your normal query here.
   }
   public static function getLinks(relation_id, $counter){
       if($counter <= 0){
          return [];
       }
       $ret = [];
       $r_ids = Relations::getLinksFromDB(r_id);
       foreach($r_ids as $r_id){
           $ret[] = Relations::getLinks($r_id, $counter - 1);
       }
       return $ret;
   }
}

两者都可以这样调用:

$ids = ['A', 'B', 'C'];
$links = [];
foreach($ids as $id){
 $links[] = Relations::getLinks($id);
}

或有深度限制

$ids = ['A', 'B', 'C'];
$links = [];
foreach($ids as $id){
 $links[] = Relations::getLinks($id, 20);
}

推荐阅读