Issue
I have a php recursive function as shown in the below:
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);
}
}
}
}
This function is working for me. but I want to get output from a variable instead of echoing inside the function. Actually I need to return
option list from the funciton.
This is how I tried it, but it doesn't work for me.
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;
}
UPDATE: This is how I call this function.
displayDropdown($catList, 0, [$cid])
This is how I create $catList
array inside while loop with the result of a query.
while ($stmt->fetch()) {
$catList[$parent][$catID] = $name;
}
Array structure as below:
Array
(
[1] => Array
(
[2] => Uncategorized
[3] => SHOW ITEMS
[4] => HORN
[5] => SWITCH
[6] => LIGHT
)
[0] => Array
(
[1] => Products
)
)
1
Hope somebody may help me out.
Solution
you need also like this $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;
}
Answered By - uingtea Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.