我有一个包含类名及其基类的数组。结构如下所示:
$list[0] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[1] = array("class"=>"ComboBox", "base"=>"Control");
$list[2] = array("class"=>"Control", "base"=>"");
$list[3] = array("class"=>"domTextArea", "base"=>"Control");
..
... so on up to 50 classes
问题是数组没有根据继承结构进行排序。在这种情况下,控件类必须位于顶部。PHP 中是否有任何函数可以根据父子关系对这种结构进行排序。生成的数组必须如下所示:
$list[0] = array("class"=>"Control", "base"=>"");
$list[1] = array("class"=>"domTextArea", "base"=>"Control");
$list[2] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[3] = array("class"=>"ComboBox", "base"=>"Control");
编辑:如果有人可以建议一种算法来对这种类型的结构进行排序,那也会很有帮助。
你可以只使用递归函数。
$list[0] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[1] = array("class"=>"ComboBox", "base"=>"Control");
$list[2] = array("class"=>"Control", "base"=>"");
$list[3] = array("class"=>"domTextArea", "base"=>"Control");
$parents = array();
foreach($list as $item) {
if (!is_array($parents[$item['base']])) {
$parents[$item['base']] = array();
}
$parents[$item['base']][] = $item['class'];
}
function calculateChilds($base, $parents) {
$result = array();
if (is_array($parents[$base])) {
foreach($parents[$base] as $child) {
$result[] = array('base' => $base, 'class' => $child);
$result = array_merge($result, calculateChilds($child, $parents));
}
}
return $result;
}
var_dump(calculateChilds('', $parents));
Thils 将输出如下:
array(4) {
[0]=>
array(2) {
["base"]=>
string(0) ""
["class"]=>
string(7) "Control"
}
[1]=>
array(2) {
["base"]=>
string(7) "Control"
["class"]=>
string(8) "ComboBox"
}
[2]=>
array(2) {
["base"]=>
string(7) "Control"
["class"]=>
string(11) "domTextArea"
}
[3]=>
array(2) {
["base"]=>
string(11) "domTextArea"
["class"]=>
string(8) "ckEditor"
}
}