如何创建一个跟踪相关对象之间路径的递归类函数?
数据:
ID Name ParentID
1 Egypt 0
2 USA 0
3 Giza 1
4 6th october 3
addressPath(4)
等函数调用应产生此输出:
埃及 - >吉萨 - > 10月6日
今天,有人发布了一个简短的功课问题,没有展示任何研究成果,并且有一些无数的downvotes。最近我因为this answer而被鼓励回答这类问题,结果我发现了一些合理的乐趣和技巧(想想code kata)。但是,在我发布答案之前,帖子已被删除,可能是因为peer pressure。无论如何,这是从我的记忆中再现的问题。
答案 0 :(得分:0)
我认为一些混淆可能来自对象和对象集合之间的区别。对于这个可能的解决方案,我为每个使用了一个类,以便该函数可以属于集合类。
递归函数本身是逐行注释的,所以我希望它足够清楚。
<?php
class related_object {
public $ID;
public $Name;
public $ParentID;
public function __construct($id, $name, $parent=0) {
$this->ID = $id;
$this->Name = $name;
$this->ParentID = $parent;
}
}
class related_object_library {
public $objects;
public function add($object) {
$this->objects []= $object;
}
public function addressPath($id, $path='') {
// iterate through each object in collection
foreach ($this->objects as $object){
// if ID matches, then return Name
if ($object->ID === $id) {
$path = $object->Name.$path;
// if it has a parent, then recurse, else just return
if (!empty($object->ParentID))
return $this->addressPath($object->ParentID,"->$path");
else return $path;
} // end if match
} // end loop
} // end function
} // end class
$collection = new related_object_library();
$collection->add(new related_object(1,'Egypt'));
$collection->add(new related_object(2,'USA'));
$collection->add(new related_object(3,'Giza',1));
$collection->add(new related_object(4,'6th october',3));
echo $collection->addressPath(4);
希望你现在正在做功课并实际研究这个主题,所以也许你很幸运能够得到这个答案。