2016-06-06 2 views
0

관련 개체 사이의 경로를 추적하는 재귀 클래스 함수를 어떻게 만듭니 까?관련 객체간에 경로를 재귀 적으로 가져 오는 방법은 무엇입니까?

데이터 :

이집트> Giza-> 10월 6일


오늘 누군가가 게시 : addressPath(4)이 출력을 생성한다 등

ID Name   ParentID 

1 Egypt   0 

2 USA   0 

3 Giza   1 

4 6th october 3 

함수 호출 어떤 r도 보이지 않는 간결한 숙제 찾는 질문 esearch 노력, 그리고 그것은 downvotes의 무의미한 숫자를했다. 최근에 나는 this answer 때문에 이런 유형의 질문에 답할 것을 권장 받았고 결과적으로 약간의 합당한 즐거움과 기술의 예리함을 발견했습니다 (code kata). 그러나 내 답변을 올릴 수 있기 전에 게시물이 삭제되었습니다. 아마도 peer pressure 때문일 수 있습니다. 여하튼, 여기 내 기억의 가장 좋은 것으로부터 재현 된 질문이있다.

답변

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); 

어쩌면이 대답 건너 충분히 운이 좋다, 희망 당신은 지금 당신의 숙제를하고 실제로 주제를 연구.

관련 문제