gpt4 book ai didi

Php pdo 使用序列进行迭代

转载 作者:行者123 更新时间:2023-11-29 11:13:02 26 4
gpt4 key购买 nike

我想按顺序显示问题和答案(先:问题然后答案)怎么可能?

$servername = "localhost";
$username = "someone";
$password = "someonepassword";
$dbname = "quiz_app";

$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$statement = $pdo->prepare("SELECT * FROM question");
$statement2 = $pdo->prepare("SELECT a.id as answer_id, a.*,
q.id as question_id, q.*
FROM answer a
inner join question q on a.question_id = q.id");


$statement->execute();
$statement2->execute();


$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$result2 = $statement2->fetchAll(PDO::FETCH_ASSOC);

$i=0;
foreach ($result as $row) {
$i++;
echo "<h5>".$i.'.'.$row['question_text']. "</h5>";
foreach ($result2 as $row2) {
echo "<input name='group". $row2['id'] ."' type='radio' id='". $row2['answer_id'] ."' />" . "<label for='". $row2['answer_id'] ."'>".$row2['answer_text']."</label>";
}
echo "<br>";
}

在此代码中,问题和答案的顺序不同(所有问题放在一起,然后是答案)我该如何解决它?

最佳答案

更逻辑地思考您正在处理的数据。第一个查询完全没有必要,您需要的一切都在第二个查询中。只需通过 q.ida.id

订购即可
$stmt = $pdo->prepare("SELECT q.*,q.id as qid,
a.*, a.id as aid
FROM question q
inner join answer a on a.question_id = q.id
ORDER BY qid, aid");

$q_and_a = $statement->fetchAll(PDO::FETCH_ASSOC);

$last_qid = NULL;
foreach ( $q_and_a as $i => $row) {
if ( $last_qid == $row['qid'] ) {
// we are starting a new question
echo "<h5>{$row['question_text']}</h5>";
$last_qid = $row['qid'];
}
// hear we are processing all the answer to the question
echo "<input name='group{$row2['qid']}' type='radio' id='{$row['aid']}'/>"
. "<label for='{$row['aid']}'>{$row['answer_text']}</label>";
}

Not sure if I got the question id and answer id info in the right place in the output, but hopefully this will give you a nudge in the right direction and you can fix any little issues yourself

关于Php pdo 使用序列进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com