我似乎无法让数组从函数中正确返回,每次运行脚本时它只是回显0,即使我已经检查过MySQL查询返回至少1行。我也尝试过使用$_GLOBALS["FORUM_ANSWERS"][] = ...
,但它仍然没有用。
public function getAnswers() {
$dbh = $this->dbh;
$id = $this->question_id;
$q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
$q->bindParam(":id", $id);
$q->execute();
$nr = $q->rowCount();
if ($nr == 0) {
echo "No Questions";
}
$_GLOBALS["FORUM_ANSWERS"] = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
array_push($_GLOBALS["FORUM_ANSWERS"], array(
"num_id" => $row["num_id"],
"question_id" => $row["question_id"],
"answer" => $row["answer"],
"name" => $row["name"],
"username" => $row["username"],
"ip" => $row["ip"],
"date" => $row["date"],
));
}
return $GLOBALS["FORUM_ANSWERS"];
}
单独文件:
$answers = $forum->getAnswers();
echo count($answers);
答案 0 :(得分:4)
您正在分配给$_GLOBALS
并返回$GLOBAL
。
你实际上并不需要使用全局数组 - 我只是将数组赋值给一个变量(在函数中初始化)并返回它。