关于 Paul Norman 的解决方案,我不知道该告诉您什么,但似乎有一个错误......我尝试了一个解决方案,它似乎满足了您示例中的依赖关系(尽管没有完全列出它们你想要的顺序...)
class Dependencies
{
private $items;
private $depends;
private $hasDependency;
public function __construct()
{
$this->items = array();
$this->depends = array();
$this->hasDependency = array();
}
public function add($item, $dependsOn = array())
{
$this->items[] = $item;
foreach ($dependsOn as $dependsOnItem)
{
$this->items[] = $dependsOnItem;
$this->depends[$dependsOnItem][] = $item;
}
$this->items = array_unique($this->items);
$this->hasDependency[$item] = $dependsOn;
}
public function getLoadOrder()
{
$order = array();
$hasChanged = true;
while (count($order) < count($this->items) && $hasChanged === true)
{
$hasChanged = false;
foreach ($this->hasDependency as $item => $dependencies)
{
if ($this->satisfied($item, $order))
{
$order[] = $item;
unset($this->hasDependency[$item]);
$hasChanged = true;
}
}
}
if (count($order) < count($this->items) && $hasChanged === false)
{
echo 'Impossible set of dependencies';
return false;
}
return $order;
}
private function satisfied($item, $addedSoFar)
{
$dependencies = $this->hasDependency[$item];
foreach ($dependencies as $dependency)
{
if (!in_array($dependency, $addedSoFar))
{
return false;
}
}
return true;
}
}
$deps = new Dependencies();
$deps->add('countries', array('menus', 'settings'));
$deps->add('dashboard', array('menus'));
$deps->add('languages', array('menus', 'settings'));
$deps->add('menus');
$deps->add('modules' , array('menus'));
$deps->add('settings' , array('menus'));
$deps->add('users' , array('menus'));
print_r($deps->getLoadOrder());