Last active
July 4, 2019 07:50
-
-
Save bizley/f74000f7196ab61a09e6b50dcc7d7b5e to your computer and use it in GitHub Desktop.
Sorts array by elements dependency [item => [items item depends on]].
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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