php - 如何在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 并加快处理速度。
谢谢你的帮助。
解决方案
简单的递归。像这样的东西
基本的
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);
}
推荐阅读
- python - 在具有分类列的熊猫数据框中,跨类别推断另一列的值
- spring-boot - 如何将不为空的@RepositoryRestResource 注入@RestController
- c# - WMI:查询类的特定实例
- android - 如何从自定义视图进行 Api 调用?
- r - 我在 R 程序中收到以下错误“if (num < 0) { 中的错误:需要 TRUE/FALSE 的缺失值”
- amazon-web-services - 如何在 cloudformation 更新上运行 ec2 UserData 脚本
- python - 使用 tk filedialog 以特定名称保存文件
- python - 在 for 循环中填充熊猫数据框
- mysql - sql查询最大值,分组依据
- android - 在适配器中观察 livedata 的问题 - android