0

所以...

class postQuery {

public function __construct($args = NULL){

    $post_type = $args['post_type'];
    $limit = $args['limit'];
    $category = $args['cat'];

    global $sql;

    $sql = $sql->query('SELECT * FROM posts');
    $sql = $sql->fetchAll(PDO::FETCH_ASSOC);
}

public function havePosts() {

    global $sql;
    global $rowNum;

    $rowNum = 0;
    $rowMax = count($sql);

    while($rowNum <= $rowMax) {
        return $rowNum;
        $rowNum++;
    }

}
}

havePosts() 函数应该在 $rowNum < $rowMax... 时运行...到目前为止一切正常...

但现在,我想用这个函数创建一个 while 语句,如下所示:

$con = new postQuery();

while($con->havePosts()){
    global $sql;
    global $rowNum;

    return $sql[$rowNum]['title'];
}

如何在函数中一一返回我的 WHILE 给出的数据?

4

2 回答 2

0

您的postQuery课程可能如下所示:

class postQuery() {

  private $currentRow = 0;

  public function havePosts() {
    global $sql;
    if ($this->currentRow == count($sql) - 1)
      return FALSE;
    $this->currentRow++;
    return $this->currentRow - 1;
  }
}

然后你可以循环浏览帖子:

while(($rowNum = $conn->havePosts()) !== FALSE) {
  echo $sql[$rowNum]['title'];
}

请注意,我的示例根本不是最佳实践。您应该避免使用全局变量和可以存储到类成员变量(例如count($sql))的大量数据。您还应该修复我的算术,以避免使用像$this->currentRow + 1.

于 2012-12-09T13:17:49.557 回答
0

将结果放入数组并返回该数组,您可以稍后访问

public function havePosts() {
  global $sql;
  global $rowNum;

  $rowNum = 0;
  $rowMax = count($sql);
  $titles=array();
 while($con->havePosts()){
    global $sql;
    global $rowNum;

   $titles[]= $sql[$rowNum]['title'];
  }

  return $titles;

}

于 2012-12-09T13:24:51.173 回答