gpt4 book ai didi

PHP递归函数问题?

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

我想为我的第一个和第四个 <ol> 添加两个不同的类属性标签,但我真的不知道如何将它添加到我的递归函数中?有人可以帮助我吗?

这是我的 PHP 脚本。

function make_list ($parent = 0, $parent_url = '') {
global $link;
echo '<ol>';

foreach ($parent as $id => $cat) {
if($cat['parent_id'] == '0'){
$url = $parent_url . $cat['url'];
echo '<li><a href="' . $url . '" title="' . $cat['category'] . ' Category Link" style="color: orange; font-weight: bold;">' . $cat['category'] . '</a>';
} else {
$url = $parent_url . $cat['url'];
// Display the item:
echo '<li><a href="' . $url . '" title="' . $cat['category'] . ' Category Link">' . $cat['category'] . '</a>';
}

if (isset($link[$id])) {
make_list($link[$id], $url);
}
echo '</li>';
}
echo '</ol>';
}

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");
if (!$dbc) {
print mysqli_error();
}

$link = array();

while (list($id, $parent_id, $category, $url, $depth) = mysqli_fetch_array($dbc)) {
$link[$parent_id][$id] = array('parent_id' => $parent_id, 'category' => $category, 'url' => $url, 'depth' => $depth);
}

make_list($link[0]);

输出

<ol>
<li>First Nested List</li>
<li>First Nested List</li>
<li>First Nested List
<ol>
<li>Second Nested List</li>
<li>Second Nested List</li>
<li>Second Nested List
<ol>
<li>Third Nested List</li>
<li>Third Nested List</li>
<li>Third Nested List
<ol>
<li>Fourth Nested List</li>
<li>Fourth Nested List</li>
<li>Fourth Nested List</li>
</ol>
</li>
<li>Third Nested List</li>
<li>Third Nested List</li>
</ol>
</li>
<li>Second Nested List</li>
<li>Second Nested List</li>
</ol>
</li>
<li>First Nested List</li>
<li>First Nested List</li>
</ol>

最佳答案

只需添加深度作为参数。然后检查它是 0 还是 4 或您需要的任何值。

function make_list ($parent = 0, $parent_url = '', $depth=0) {
...
make_list($link[$id], $url, $depth+1);
...

关于PHP递归函数问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3517719/

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