Skip to content

Instantly share code, notes, and snippets.

@bizley
Last active July 4, 2019 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bizley/f74000f7196ab61a09e6b50dcc7d7b5e to your computer and use it in GitHub Desktop.
Save bizley/f74000f7196ab61a09e6b50dcc7d7b5e to your computer and use it in GitHub Desktop.
Sorts array by elements dependency [item => [items item depends on]].
<?php
function sortByDependency($input)
{
$output = [];
$checkList = [];
$inputCount = count($input);
// while not all items are resolved:
while ($inputCount > count($output)) {
$done = false;
foreach ($input as $name => $dependencies) {
if (array_key_exists($name, $checkList)) {
// item already in resultset
continue;
}
$resolved = true;
foreach ($dependencies as $dependency) {
if (!array_key_exists($dependency, $checkList)) {
// there is a dependency that is not met:
$resolved = false;
break;
}
}
if ($resolved) {
//all dependencies are met:
$checkList[$name] = true;
$output[] = $name;
$done = true;
}
}
if (!$done) {
throw new Exception("Circular dependency");
}
}
return $output;
}
var_dump(sortByDependency([
'A' => ['B'],
'B' => ['C'],
'C' => ['D'],
'D' => [],
]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment