Currently I'm using these three functions, that in the end produces a JSON array. I went this way so that I could fetch data from a specific table. But now it just seems bloated and poorly written, mixed with stdClass and arrays.
public static function getFraga($quiz_id = false)
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "SELECT * FROM questions";
$arg = false;
if($quiz_id) {
$sql .= " WHERE quiz_id = :quiz_id";
$arg = array(':quiz_id' => $quiz_id);
}
$query = $database->prepare($sql);
if($arg) {
$query->execute($arg);
} else {
$query->execute();
}
$data = $query->fetchAll();
$data = json_decode(json_encode($data), true);
$out = array();
foreach($data as $key => $row) {
$out[$row['id']] = $row;
}
return $out;
}
public static function getAnswers()
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "SELECT * FROM choices";
$query = $database->prepare($sql);
$query->execute();
$data = $query->fetchAll();
$data = json_decode(json_encode($data), true);
$out = array();
foreach($data as $key => $row) {
$out[$row['id']] = $row;
}
return $out;
}
public static function qAndA($quiz_id = false)
{
$questions = Self::getFraga($quiz_id);
$answers = Self::getAnswers();
$combined = array();
foreach($answers as $answer) {
if(!isset($questions[$answer['question_id']])) continue;
$q_key = 'question-'.$answer['question_id'];
if(!isset($combined[$q_key])) {
$combined[$q_key] = $questions[$answer['question_id']];
}
$combined[$q_key]['answer'][$answer['id']] = $answer;
}
return $combined;
}
And I call the qAndA()
to get this result, with json_encode()
:
{
"question": {
"question-5": {
"id": "5",
"content": "Har jag laddad upp en bild?",
"source": "99",
"image_url": "156ebc02fd6281_kljqpiohfngme.jpeg",
"lastmodified": "2016-03-18 09:45:35",
"quiz_id": "1",
"answer": {
"17": {
"id": "17",
"content": "Nej",
"correct": "1",
"question_id": "5"
},
"18": {
"id": "18",
"content": "ja",
"correct": "0",
"question_id": "5"
},
"19": {
"id": "19",
"content": "kanske",
"correct": "0",
"question_id": "5"
},
"20": {
"id": "20",
"content": "vet inte",
"correct": "0",
"question_id": "5"
}
}
}
}
}
Narrow it down to one function? Other improvements?