2012-05-03 235 views
1

我有一個函數,可以通過echo獲取所有正確的值,但是當我無法弄清楚如何獲取整個數組時返回。有人能幫我找出所有的小孩用戶嗎?從遞歸函數返回一個值

$useridarray[] = $userid; 
    getchildren($useridarray, $useridarray); 

    function getchildren($array, $totalarray) 
    { 
     foreach($array as $arr) 
     { 
      $db_name = "dbname"; 
      $connection = @mysql_connect("localhost", "username", "password") or die(mysql_error()); 
      $db = @mysql_select_db($db_name, $connection) or die(mysql_error()); 
      $sql = " 
        select * 
        from users 
        where creator = '$arr' 
        "; 
      $result = @mysql_query($sql, $connection) or die(mysql_error()); 
      while($row = mysql_fetch_array($result)) 
      { 
       $newchildren[] = $row['id']; 
       $totalarray[] = $row['id']; 
       //echo $row['id'] . ' '; 
      } 
      mysql_close(); 
      getchildren($newchildren, $totalarray); 
     } 
    } 
+1

只是在實際和性能方面,我會創建一個函數來創建連接並選擇數據庫,並將這些細節傳遞給您的函數。將減少創建和關閉連接的開銷。 –

回答

1

您需要pass by reference­Docs

function getchildren($array, &$totalarray) 
          ^

用法:

$useridarray[] = $userid; 
getchildren($useridarray, $useridarray); 
var_dump($useridarray); # your result 
0

您需要添加返回之前

mysql_close(); 
return getchildren($newchildren, $totalarray); 
0

我不熟悉PHP語法,但你可能想要實施一個「停止標準」來返回你的結果。因此,在您的實例中,您似乎希望getChildren返回localResults +遞歸getChildren結果,並在您通過foreach循環時遞增累計。