我有一個php遞回函式,如下所示:
function displayDropdown(&$catList, $parent, $current=[], $level=0) {
if ($parent==0) {
foreach ($catList[$parent] as $catID=>$nm) {
displayDropdown($catList, $catID, $current);
}
}
else {
foreach ($catList[$parent] as $catID=>$nm) {
$sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';
echo "<option value='$catID' $sel>$nm</option>\n";
if (isset($catList[$catID])) {
displayDropdown($catList, $catID, $current, $level 1);
}
}
}
}
這個功能對我有用。但我想從變數中獲取輸出,而不是在函式內部回顯。實際上我需要return從功能中選擇串列。
這就是我嘗試過的方法,但它對我不起作用。
function displayDropdown(&$catList, $parent, $current=[], $level=0) {
$optionsHTML = '';
if ($parent==0) {
foreach ($catList[$parent] as $catID=>$nm) {
displayDropdown($catList, $catID, $current);
}
}
else {
foreach ($catList[$parent] as $catID=>$nm) {
$sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';
$optionsHTML .= "<option value='$catID' $sel>$nm</option>\n";
if (isset($catList[$catID])) {
displayDropdown($catList, $catID, $current, $level 1);
}
}
}
//return displayDropdown($optionsHTML);
return $optionsHTML;
}
更新: 這就是我呼叫這個函式的方式。
displayDropdown($catList, 0, [$cid])
這就是我$catList在 while 回圈中使用查詢結果創建陣列的方式。
while ($stmt->fetch()) {
$catList[$parent][$catID] = $name;
}
陣列結構如下:
Array
(
[1] => Array
(
[2] => Uncategorized
[3] => SHOW ITEMS
[4] => HORN
[5] => SWITCH
[6] => LIGHT
)
[0] => Array
(
[1] => Products
)
)
1
希望有人可以幫助我。
uj5u.com熱心網友回復:
你也需要這樣$optionsHTML .= displayDropdown(...)
function displayDropdown(&$catList, $parent, $current=[], $level=0) {
$optionsHTML = '';
if ($parent==0) {
foreach ($catList[$parent] as $catID=>$nm) {
$optionsHTML .= displayDropdown($catList, $catID, $current);
}
}
else {
foreach ($catList[$parent] as $catID=>$nm) {
$sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';
$optionsHTML .= "<option value='$catID' $sel>$nm</option>\n";
if (isset($catList[$catID])) {
$optionsHTML .= displayDropdown($catList, $catID, $current, $level 1);
}
}
}
return $optionsHTML;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474874.html
