Will build the tree and make the menu.
PHP Code:
<?php
class Animal {
protected $animals;
protected $name;
public function __construct($name) {
$this->animals = array();
$this->name = $name;
}
public function matches($pk) {
return strcasecmp($pk,$this->getName())==0;
}
public function getName() {
return $this->name;
}
public function addAnimal(Animal $animal) {
$this->animals[] = $animal;
}
public function getAnimals() {
return $this->animals;
}
public function hasAnimals() {
return empty($this->animals)?false:true;
}
public function hasAnimalByName($name) {
foreach($this->animals as $animal) {
if($animal->matches($name)==true) {
return true;
}
}
return false;
}
public function getAnimalByName($name) {
foreach($this->animals as $animal) {
if($animal->matches($name)==true) {
return $animal;
}
}
}
public function addRow($row,$map,$runner=0) {
if(!array_key_exists($runner,$map)) return;
$key = $map[$runner];
if(!array_key_exists($key,$row)) return;
if(is_null($row[$key])) return;
if($this->hasAnimals()===true && $this->hasAnimalByName($row[$key])===true) {
$childAnimal = $this->getAnimalByName($row[$key]);
} else {
$childAnimal = new Animal($row[$key]);
$this->addAnimal($childAnimal);
}
$childAnimal->addRow($row,$map,($runner+1));
}
public function buildMenu() {
if($this->hasAnimals()===true) {
echo '<ul>',"\n";
foreach($this->getAnimals() as $item) {
if($item->hasAnimals()===true) {
echo '<li>',$item->getName();
$item->buildMenu();
echo '</li>',"\n";
} else {
echo '<li>',$item->getName(),'</li>',"\n";
}
}
echo '</ul>',"\n";
}
}
}
$animals = array();
$result = array(
array('animal','birdie',null,null)
,array('animal','doggie','companion','chihuahua')
,array('animal','doggie','companion','poodle')
);
foreach($result as $row) {
$currentRootAnimal = null;
if(!empty($animals)) {
foreach($animals as $animal) {
if($animal->matches($row[0])===true) {
$currentRootAnimal = $animal;
break;
}
}
} else {
$currentRootAnimal = new Animal($row[0]);
$animals[] = $currentRootAnimal;
}
$currentRootAnimal->addRow($row,array(1,2,3));
}
if(!empty($animals)) {
echo '<ul id="animal-menu">';
foreach($animals as $animal) {
if($animal->hasAnimals()===true) {
echo '<li>',$animal->getName();
$animal->buildMenu();
echo '</li>',"\n";
} else {
}
}
echo '</ul>';
}
?>
Bookmarks