0
我有一个具有依赖关系的文件数组。我需要对它们进行排序,以便所有依赖文件在其依赖关系之后进行索引。我已经用forEach循环做了很多尝试,while循环,但是一旦移动了依赖关系,这些循环就不会考虑以前的迭代,并且索引元素会失序。PHP排序依赖项数组列表 - 拓扑排序
我有数据的简化版本我正在与工作:
$dependencies = array(
array(
'handle' => 'jquery',
'requires' => array(
'jquery-core',
'jquery-migrate'
)
),
array(
'handle' => 'jquery-migrate',
'requires' => array()
),
array(
'handle' => 'common',
'requires' => array(
'utils',
'jquery',
'jquery-core',
'jquery-migrate',
'jquery-effects-core',
'backbone'
)
),
array(
'handle' => 'jquery-effects-core',
'requires' => array(
'jquery',
'jquery-core',
'jquery-migrate'
)
),
array(
'handle' => 'backbone',
'requires' => array(
'underscore',
'jquery'
)
),
array(
'handle' => 'underscore',
'requires' => array()
),
array(
'handle' => 'utils',
'requires' => array()
),
array(
'handle' => 'jquery-core',
'requires' => array()
)
);
如果[把手]出现在一个元素[需要]数组,该元素需要被提前移动的指示的要求]元素,同时保持先前解释的任何其他依赖关系。
function moveEle(&$array, $a, $b){
$out = array_splice($array, $a, 1);
array_splice($array, $b, 0, $out);
}
foreach($dependencies as $i=>$dependency){
if(count($dependency['requires'])>0){
$itr = count($dependency['requires']);
echo $dependency['handle']."<br/>";
while($itr > 0){
// loop through current files required files
foreach($dependency['requires'] as $k=>$dep){
// loop through dependencies array again to find required file handle
echo "-- " . $dep . "<br/>";
foreach($dependencies as $j=>$jDep){
// $j = index in dependencies array of required file, $i = index in dependencies array of dependent file.
if($dep === $jDep['handle'] && $j > $i){
echo "found " . $jDep['handle'] . "@ " . $j."<br/>";
moveEle(&$dependencies, $j, $i);
}
}
$itr--;
}
}
}
}
我把它有可能是做一些这方面的递归的方式就是有点超出了我的技能的范围在这一点上。任何帮助将不胜感激。
我没有找到这个解决方案: PHP Order array based on elements dependency 它不工作,但是,一旦阵列到达150个文件(实际数据大小),超时或采取一个非常长的时间。如果存在的话,我想要一个更有效的解决方案。