对不起-标题真的很差,但是想不起来怎么写!
我正在创建一个像这样的文件夹结构数组:
表中的每个条目都有三个字段:
| parent id | route | label |
|-----------|-------|------------|
| 1 | | account |
| 2 | 1 | section 1 |
| 3 | 1 | section 2 |
| 4 | 1/2 | s1 options |
| 5 | 1/3 | s2 options |
| 6 | 1/2/4 | settings |
| 7 | 1/3/5 | language |
这看起来像这样:
account /
account / section 1 /
account / section 2 /
account / section 1 / s1 options /
account / section 2 / s2 options /
account / section 1 / s1 options / settings
account / section 2 / s2 options / language
要创建此文件,请使用route
及其parent id
来解析label
。到目前为止,一切都很简单。
我确定您会感激的,我想将其列出为:
account /
account / section 1 /
account / section 1 / s1 options /
account / section 1 / s1 options / settings
account / section 2 /
account / section 2 / s2 options /
account / section 2 / s2 options / language
这是我遇到问题的地方!我在sql查询和各种数组选项中都尝试了不同的排序选项,但是我陷入了困境。
我有一个页面,用户可以通过先选择父文件夹然后添加新文件夹名称来创建新文件夹,因此我无法控制文件夹结构的构建方式或顺序。>
目前,我正在尝试避免过长而复杂的事情,因为我敢肯定必须有一种简单的方法来做...我只是找不到它。
建议/解决方案很有价值! :)
SQL-
$q1 = $dbp->prepare("SELECT * FROM `structure`");
$q1->execute();
while ($d1 = $q1->fetch()) {
$structure_parent[] = $d1['parent'];
$structure_route[] = $d1['route'];
$structure_label[] = $d1['label'];
$structure[$d1['parent']] = $d1['label'];
}
选择-
<select id="parent" name="parent">
<?php
$p = 0;
while($p < count($structure_parent)) {
// build route map
$route = explode("/", $structure_route[$p]);
$s = 0;
while($s < count($route)) {
$route_mapping[] = $structure[$route[$s]];
$s++;
}
if($structure_route[$p] > "") $routemap = implode(" / ", $route_mapping)." / ";
else $routemap = "";
unset($route_mapping);
?>
<option value="<?php echo $structure_parent[$p]; ?>"><?php echo " / ".$routemap.$structure_label[$p]; ?></option>
<?php
$p++;
}
?>
</select>
答案 0 :(得分:1)
您可以简单地使用array_combine
和array_column
创建标签图,并使用strtr
(documentation)来交换路线。
考虑以下示例(我跳过了数据库提取,仅使用数据初始化数组):
$arr = [];
$arr[] = array("id" => 1, "route" => "", "label" => "account");
$arr[] = array("id" => 2, "route" => "1", "label" => "section 1");
$arr[] = array("id" => 3, "route" => "1", "label" => "section 2");
$arr[] = array("id" => 4, "route" => "1/2", "label" => "s1 options");
$arr[] = array("id" => 5, "route" => "1/3", "label" => "s2 options");
$arr[] = array("id" => 6, "route" => "1/2/4", "label" => "settings");
$arr[] = array("id" => 7, "route" => "1/3/5", "label" => "language");
$labels = array_combine(array_column($arr, "id"), array_column($arr, "label")); // labels will be mapping between id to label
foreach($arr as $e) {
$ans[] = strtr($e["route"], $labels) . "/" . $e["label"]; //build path according to route and add your label
}
sort($ans);
现在$ans
会让您想要输出。