提问人:nameless 提问时间:1/5/2023 最后编辑:RiggsFollynameless 更新时间:1/5/2023 访问量:78
具有关联树的多维数组
Multidimensional array with affiliate tree
问:
我正在开发一个带有附属逻辑的系统,结构中最多有 3 个级别。
我已经让它完美地工作了 2 层。这是我用于 2 层的代码。我正在使用无脂肪框架作为PHP框架,不过那里应该没什么大不了的(认为代码应该在不了解框架的情况下也能理解)......
PHP格式:
$firstLevel = $db->exec('SELECT * FROM users WHERE sponsorID=:sponsorID', array(':sponsorID' => $_SESSION['userid']));
$affiliateTree = [];
foreach ($firstLevel as $fl) {
$secondLevel = $db->exec('SELECT * FROM users WHERE sponsorID=:sponsorID', array(':sponsorID' => $fl["ID"]));
$affiliateTree[$fl["username"]] = [];
foreach ($secondLevel as $sl) {
$affiliateTree[$fl["username"]][] = $sl["username"];
}
}
$f3->set('affiliateTree', $affiliateTree);
HTML格式:
<repeat group="{{ @affiliateTree }}" key="{{ @affKey }}" value="{{ @affVal }}">
<li>
<details open>
<summary>{{@affKey}}</summary>
<check if="{{@affVal}}">
<true>
<ul>
<repeat group="{{@affVal}}" key={{@newAffKey}} value="{{@affiliate}}">
<li>{{@affiliate}}</li>
</repeat>
</ul>
</true>
</check>
</details>
</li>
</repeat>
这导致了一个我想要的列表,如下所示:
-paul
-olaf
-jeanett
-christine
-john
-peter
-tom
-caroline
我的数据库表看起来像这样(尽管如果需要,愿意修改):
ID | SponsorID | username
1 | NULL | master
2 | 1 | paul
3 | 1 | olaf
4 | 3 | jeanettt
5 | 3 | christine
6 | 1 | john
7 | 6 | peter
8 | 6 | tom
9 | 6 | caroline
现在我尝试修改第三层的代码,但失败了。所以基本上,如果卡罗琳也提到某人,那也应该显示出来(所以只是一个额外的层)......
如何修改代码(或编写新代码)以正确完成此操作?我尝试过以下方法:
PHP的
foreach ($firstLevel as $fl) {
$secondLevel = $db->exec('SELECT * FROM users WHERE sponsorID=:sponsorID', array(':sponsorID' => $fl["ID"]));
$affiliateTree[$fl["username"]] = [];
foreach ($secondLevel as $sl) {
$thirdLevel = $db->exec('SELECT * FROM users WHERE sponsorID=:sponsorID', array(':sponsorID' => $sl["ID"]));
$affiliateTree[$fl["username"]][] = [];
foreach ($thirdLevel as $tl){
$affiliateTree[$fl["username"]][$sl["username"]][] = $tl["username"];
}
}
}
HTML格式:
<repeat group="{{ @affiliateTree }}" key="{{ @affKey }}" value="{{ @affVal }}">
<li>
<details open>
<summary>{{@affKey}}</summary>
<check if="{{@affVal}}">
<true>
<ul>
<repeat group="{{@affVal}}" key="{{@newAffKey}}" value="{{@affiliate}}">
<li>
<details open>
<summary>{{@newAffKey}}</summary>
<check if="{{@affiliate}}">
<true>
<ul>
<repeat group="{{@affiliate}}" value="{{@thirdLiner}}">
<li>{{@thirdLiner}}</li>
</repeat>
</ul>
</true>
</check>
</details>
</li>
</repeat>
</ul>
</true>
</check>
</details>
</li>
</repeat>
然而,这根本不起作用。除了有一些带有“0”的列表元素外,许多用户由于某种原因而丢失......
我怎样才能让它工作?有什么建议吗?如果有更有效的方法,我也要彻底改变代码和数据库......
答: 暂无答案
评论