在php中制作递归函数

时间:2014-03-06 00:58:22

标签: php recursion

我试图使递归函数从数据库构建数据数组。

此函数查看数据库并获取组名和ID,并将id放在辅助数组中,将名称放在不同的数组中。

private function Groups()
{
  $helperArray = array();
  $this->grouplist = array();
  $functionRun = 0;

  $query = "SELECT GroupName, Groups.idGroup  
            FROM Groups
            INNER JOIN Members
            ON Groups.idGroup = Members.idGroup
            WHERE Members.idMember = ? ";

            //prepare query and execute
  if($stmt = $this->connection->prepare($query))
  {

    $stmt->bind_param('s', $this->id);
    $stmt->execute();
    $stmt->bind_result($GroupName, $idGroup);
    $stmt->store_result();
    $groupNum = $stmt->num_rows;

    while ($stmt->fetch()) 
    {
       $helperArray[] = $idGroup;
       $this->grouplist[] = array("Group ID"=>$idGroup,"Group Name"=>$GroupName);

    }

  }

  if ($functionRun > $groupNum) 
  {
      echo 'function done';


  }

  else 
  {
    $this->getGroups($functionRun, $helperArray, $helperVariable);
  }

}

此函数选择辅助数组中每个组中的所有成员,并将它们添加到组列表数组中。此功能的运行量与组数量相同。它每次运行时都会增加functionRan变量。

private function getGroups($functionRun, $helperArray, $helperVariable)
{


  $query = "SELECT Users.Username
             FROM Members
             INNER JOIN Users
             ON Members.idMember = Users.idUsers
             WHERE idGroup = ? ";

  $helperVariable = $helperArray[$functionRun];

  if($stmt = $this->connection->prepare($query))
  {
    $stmt->bind_param('s', $helperVariable);
    $stmt->execute();
    $stmt->bind_result($username);

  }

     while ($stmt->fetch()) 
     {

       array_push($this->grouplist[$functionRun], $username);

     }

$functionRun++;

$this->Groups();
}

我得到的错误是

致命错误:在第170行的/webroot/signin.php中调用非对象的成员函数fetch()

1 个答案:

答案 0 :(得分:0)

你可能遇到的问题。 (你没有提供行信息或文件名。所以我不知道这是你的问题,只是它可能是)。

getGroups()中,if和while不在同一个块中。

你有。

if($stmt = $this->connection->prepare($query))
  {
    $stmt->bind_param('s', $helperVariable);
    $stmt->execute();
    $stmt->bind_result($username);

  }

     // Outside the if block
     while ($stmt->fetch()) 
     {
       array_push($this->grouplist[$functionRun], $username);
     }

你想要。

if($stmt = $this->connection->prepare($query))
  {
    $stmt->bind_param('s', $helperVariable);
    $stmt->execute();
    $stmt->bind_result($username);

    // Inside the If Block
    while ($stmt->fetch()) 
    {
       array_push($this->grouplist[$functionRun], $username);
    }
  }

while ($stmt->fetch())可以在$stmt上调用falsenull