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

How I use return inside a recursive functions in php

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

这就是我在 while 循环中使用查询结果创建 $catList 数组的方式。

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;
}