Can anyone show me an example of how to sort this array dependent on the dependency key of each array. I would like the array to be in order of the dependency so jquery first th
There are probably a number of different approaches to solving this. Here I loop over the array of scripts, removing any dependencies that are already in the output array before adding any scripts with no further dependencies.
I didn't test it to destruction but it works with your example.
$sorted = [];
while ($count = count($scripts)) {
// Remove any met dependencies.
foreach ($scripts as $script_id => $script) {
if (isset($script["dependency"])) {
foreach ($script["dependency"] as $dep_id => $dep) {
if (isset($sorted[$dep])) {
unset($scripts[$script_id]["dependency"][$dep_id]);
}
}
if (!count($scripts[$script_id]["dependency"])) {
unset($scripts[$script_id]["dependency"]);
}
}
}
// Add scripts with no more dependencies to the output array.
foreach ($scripts as $script_id => $script) {
if (!isset($script["dependency"])) {
$sorted[$script["name"]] = $script;
unset($scripts[$script_id]);
}
}
if (count($scripts) == $count) {
die("Unresolvable dependency");
}
}
var_dump(array_values($sorted));
/*
array (size=5)
0 =>
array (size=3)
'name' => string 'jquery' (length=6)
'version' => string '1.1' (length=3)
'file' => string 'vendor/jquery/jquery.js' (length=23)
1 =>
array (size=3)
'name' => string 'cookie' (length=6)
'version' => string '1.0' (length=3)
'file' => string 'vendor/cookie/cookie.js' (length=23)
2 =>
array (size=3)
'name' => string 'bootstrap' (length=9)
'version' => string '1.0' (length=3)
'file' => string 'vendor/bootstrap/js/bootstrap.js' (length=32)
3 =>
array (size=3)
'name' => string 'checkbox' (length=8)
'version' => string '1.0' (length=3)
'file' => string 'vendor/checkbox/checkbox.js' (length=27)
4 =>
array (size=3)
'name' => string 'admin' (length=5)
'version' => string '1.0' (length=3)
'file' => string 'vendor/admin/code.js' (length=20)
*/