我如何在 php 的递归函数中使用 return

乌努库

我有一个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

希望有人可以帮助我。

温茶

你也需要这样$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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章