Php 阵列运算
如何移动以适应数组中问题的答案,或者如何进行sql查询以获得所需的效果?我已经厌倦了这几天了Php 阵列运算,php,sql,arrays,join,Php,Sql,Arrays,Join,如何移动以适应数组中问题的答案,或者如何进行sql查询以获得所需的效果?我已经厌倦了这几天了 <?php public function getQuestions() { $sql = 'SELECT * FROM questions'; $result = Database::query($sql); while ($row = mysql_fetch_assoc($result)) { $quest
<?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
(
[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
)
)
输出:
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;
}
self::$answers[$qid] = $db->getAnswers($qid);
问题在于这一行:
foreach( self::$questions as $q )
{
$qid = $q['qid'];
self::$answers[$qid] = $db->getAnswers($qid);
}
ID为“1”的问题将被置于数组的第0个位置,因此所有答案将以1结束
一个潜在的解决办法是改变:
foreach( self::$questions as $idx=>$q )
{
$qid = $q['qid'];
self::$answers[$idx] = $db->getAnswers($qid);
}
致:
问题在于这一行:
foreach( self::$questions as $q )
{
$qid = $q['qid'];
self::$answers[$qid] = $db->getAnswers($qid);
}
ID为“1”的问题将被置于数组的第0个位置,因此所有答案将以1结束
一个潜在的解决办法是改变:
foreach( self::$questions as $idx=>$q )
{
$qid = $q['qid'];
self::$answers[$idx] = $db->getAnswers($qid);
}
致:
你能描述一下你最终需要得到的数组结构吗?你能描述一下你最终需要得到的数组结构吗?