MySQL 本身无法返回这样的多维数组,只能返回一个二维数组,其中一级是行,二级是列。
您必须自己迭代结果集并构建数组。
在 PDO 中,你会做这样的事情:
try {
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT * FROM questions INNER JOIN answers ON questions.questionId=answers.questionId");
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach ($row as $column => $value) {
if ($column != "answerId") {
$result[$row["questionId"]][$column] = $value;
}
}
$result[$row["questionId"]][$row["answerId"]] = $row["text"];
}
}
catch (PDOException $e) {
//Todo: Error Handling Here
}
这给了我以下结果(你的可能看起来不同):
array (size=2)
1 =>
array (size=9)
'questionId' => string '1' (length=1)
'title' => string 'b' (length=1)
'category' => string 'letters' (length=7)
'correctAnswerID' => string '2' (length=1)
'text' => string 'd' (length=1)
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
4 => string 'd' (length=1)
2 =>
array (size=9)
'questionId' => string '2' (length=1)
'title' => string 'd' (length=1)
'category' => string 'letters' (length=7)
'correctAnswerID' => string '8' (length=1)
'text' => string 'd' (length=1)
5 => string 'a' (length=1)
6 => string 'b' (length=1)
7 => string 'c' (length=1)
8 => string 'd' (length=1)