0
如何移動以適應數組中的問題的答案或如何使SQL查詢獲得所需的效果?這幾天我厭倦了這種遺憾。陣列操作
<?php
public function getQuestions()
{
$sql = 'SELECT * FROM questions';
$result = Database::query($sql);
while ($row = mysql_fetch_assoc($result)) {
$questions[] = $row;
}
return $questions;
}
public function getAnswers($qid)
{
$sql = 'SELECT idq, answer, truth FROM answers WHERE idq = '.$qid;
$result = Database::query($sql);
while ($row = mysql_fetch_assoc($result))
{
$answers[] = $row;
}
return $answers;
}
public static function array_add($a1, $a2)
{
$aRes = $a1;
foreach (array_slice(func_get_args(), 1) as $aRay)
{
foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
$aRes += $aRay;
}
return $aRes;
}
public static function getQuiz()
{
$db = new Database();
self::$questions = $db->getQuestions();
foreach(self::$questions as $q)
{
$qid = $q['qid'];
self::$answers[$qid] = $db->getAnswers($qid);
}
$s = Quiz::array_add(self::$questions, self::$answers);
print "<pre>";
print_r($s);
print "</pre>";
}
?>
輸出:
Array
(
[0] => Array
(
[qid] => 1
[question] => Bunty szlachty pod has?ami obrony praw nazywamy?
)
[1] => Array
(
[qid] => 2
[question] => Kto dowodzi? wojskami kozackimi podczas powstania Chmielnickiego?
[0] => Array
(
[idq] => 1
[answer] => liberum veto
[truth] => 1
)
[1] => Array
(
[idq] => 1
[answer] => jurydyki
[truth] => 0
)
[2] => Array
(
[idq] => 1
[answer] => rokosze
[truth] => 0
)
)
[2] => Array
(
[qid] => 3
[question] => W którym roku odby?a si?, morska, bitwa pod Oliw??
[0] => Array
(
[idq] => 2
[answer] => Bohdan Chmielnicki
[truth] => 1
)
[1] => Array
(
[idq] => 2
[answer] => Gustaw II Adolf
[truth] => 0
)
[2] => Array
(
[idq] => 2
[answer] => Iwan IV Gro?ny
[truth] => 0
)
)
[3] => Array
(
[0] => Array
(
[idq] => 3
[answer] => 1627
[truth] => 1
)
[1] => Array
(
[idq] => 3
[answer] => 1608
[truth] => 0
)
[2] => Array
(
[idq] => 3
[answer] => 1654
[truth] => 0
)
)
)
我試過這個解決方案,但是我需要分別有答案:
function get_quiz()
{
$sql = 'SELECT question, GROUP_CONCAT(answer ORDER BY answer SEPARAtoR " ") as answers
FROM questions
LEFT JOIN answers ON (questions.qid=answers.idq)
GROUP BY answers.idq;';
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$quiz[] = $row;
}
return $quiz;
}
輸出:
Array
(
[0] => Array
(
[question] => Bunty szlachty pod has?ami obrony praw nazywamy?
[answers] => jurydyki liberum veto rokosze
)
[1] => Array
(
[question] => Kto dowodzi? wojskami kozackimi podczas powstania Chmielnickiego?
[answers] => Bohdan Chmielnicki Gustaw II Adolf Iwan IV Gro?ny
)
[2] => Array
(
[question] => W którym roku odby?a si?, morska, bitwa pod Oliw??
[answers] => 1608 1627 1654
)
)
你能描述陣列的結構,你到底需要獲得? – Nemoden 2011-04-14 11:40:12