php - How to recursively get path between related objects? -


how create recursive class function trace path between related objects?

data:

id  name          parentid  1   egypt         0  2   usa           0  3   giza          1  4   6th october   3 

function call such addresspath(4) should produce output:

egypt->giza->6th october


today posted terse homework-looking question did not show research effort, , had gratuitous number of downvotes. encouraged answer type of question because of this answer, , i've found reasonable enjoyment , sharpening of skills result (think code kata). however, post deleted before post answer, maybe because of peer pressure. @ rate, here question reproduced best of memory.

i think of confusion may have come distinction between object , collection of objects. possible solution, used class each function belong collection class.

the recursive function commented line-by-line, hope it's clear enough.

<?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 $object){        // if id matches, return name       if ($object->id === $id) {         $path = $object->name.$path;          // if has parent, recurse, else 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); 

hopefully you're doing homework , researching subject, maybe you're lucky enough come across answer.