嗨,我有一个数据库表,这是自引用,基本上它包含了所有的物种和分类级别。例如,我们在下面有一条海龟记录
tsn_id name rank_id parent_id
123 turtle 220 349这个海龟记录的父记录是turtle_family记录(在同一个表中),直到parent_id为0为止。0表示动物王国(animalia parent_id 0)
tsn_id name rank_id parent_id
349 turtle_family 210 465我想要像海龟一样攀登每一个物种的记录。这是我的尝试
<?php
function get_each_species_record(){
$db = dbConnect();
$query= "select * from species_records where rank_id = 220"; //this rank_id is species
$result = $db -> Execute($query);
while($row=$result->FetchRow())
{
$tsn_id= $row['tsn'];
$complete_name = $row['complete_name'];
$parent_tsn = $row['parent_tsn'];
$rank = $row['rank_id'];
//* My objective *
//for each species
//take its parent tsn
//where tsn = parent tsn
//take that parents tsn
//where tsn = parent tsn
//till parent tsn = 0
climbtree($tsn_id);
}
}
//recursive function for each species
function climbtree($tsn_id){
if($parent_tsn == 0){
return 1; //quit and go onto next speices record?
}
else{
$queryone= 'select * from species_records where tsn = $parent_tsn';
$resultone = $db -> Execute($queryone);
return climbtree($tsn_id);
}
}
?>发布于 2013-07-18 14:42:47
function get_species($specie_id, $db = null) {
if ($specie_id === '0') {
return array();
}
if ($db === null) {
$db = dbConnect();
}
$query = "SELECT * FROM species_records WHERE rank_id = $specie_id";
$result = $db->Execute($query);
$row = $result->FetchRow();
return array_merge($row, array('parent' => get_species($row['parent_tsn'], $db);
}这将很好地完成递归,还没有测试array_merge是否会以您希望的方式显示结果,但这基本上会给你一个关联数组,每个动物都有它的父数组,直到它到达它的父数组是一个空数组。
我还在里面处理了数据库连接,这样您就不会在每一层都重新创建连接。
这在某种程度上是一个冗余的递归,我建议你为每个动物都有一个缓存表,这个缓存表被插入到创建它的父级的系统中,所以每当你想要检查一个动物的前身时,你可以只做一个SELECT而不是递归。
i.e
TABLE species_records_familiy_tree
tsn_id | parents
123 | 0,2,36,77,463,349https://stackoverflow.com/questions/17716103
复制相似问题