"combobox", array ("countryStore"-6ren">
gpt4 book ai didi

php - 基于父子关系对数组进行排序的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:30 24 4
gpt4 key购买 nike

我有一个控件数组,其中包含名称和要首先呈现的控件列表。以下是数组:

$controls [0] = array ("name" => "combobox", array ("countryStore", "center" ) );
$controls [1] = array ("name" => "docBody", array () );
$controls [2] = array ("name" => "top", array ("docBody" ) );
$controls [3] = array ("name" => "button1", array ("formPane" ) );
$controls [4] = array ("name" => "center", array ("docBody" ) );
$controls [5] = array ("name" => "text1", array ("formPane" ) );
$controls [6] = array ("name" => "countryStore", array ("center" ) );
$controls [7] = array ("name" => "formPane", array ("center" ) );

我需要以正确的顺序排列控件数组,这样每当我渲染一个控件时,它的所有先决条件控件都已被渲染。

Is there any function in PHP that can sort this kind of relationship?

要求的输出

$controls [0] = array ("name" => "docBody", array () );
$controls [1] = array ("name" => "top", array ("docBody" ) );
$controls [2] = array ("name" => "center", array ("docBody" ) );
$controls [3] = array ("name" => "formPane", array ("center" ) );
$controls [4] = array ("name" => "countryStore", array ("center" ) );
$controls [5] = array ("name" => "combobox", array ("countryStore", "center" ) );
$controls [6] = array ("name" => "button1", array ("formPane" ) );
$controls [7] = array ("name" => "text1", array ("formPane" ) );

排序后的代码:

$sortedArray = $SortControls($controls);
foreach ($sortedArray as $control) {
System->getControl($control['name'])->render();
}

最佳答案

我不熟悉PHP,但是...

您的数据可用于定义图形,其中节点是您的实体(例如“text1”、“formPane”),它们之间的依赖关系是有向边。

如果这个有向图是无环的(DAG),那么topological sorting是实现所需排序的简单算法。

这个算法也可以检测到一个循环,这意味着这样的排序是不可能的。

关于php - 基于父子关系对数组进行排序的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21510591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com