2011-05-12 41 views
0

我的方法返回mysqli_fetch_assoc的答案數組。我嘗試根據索引提取答案。結果與預期不符。我會得到相同的答案(應該是三個答案)。如何從mysqli_fetch_assoc獲取數組?

方法:

function getAnswers($id_question) 
{ 
    $sql = 'SELECT * FROM answers WHERE question_id = '. $id_question; 

    $this->db->query($sql); 
    while ($answers = $this->db->fetchAssoc()) 
    { 
     return $answers; 
    } 
} 

使用:

$answers = getAnswers(1); 
foreach($answers as $a) 
{ 
    echo $a['answer']; 
} 
echo '<pre>'; 
print_r($answers); 
echo '</pre>'; 

出來:

11a1 
Array 
(
    [id_answer] => 1 
    [question_id] => 1 
    [answer] => answer 1 
    [truth] => 1 
) 

回答

1

你只返回了第一盤。您將不得不將數據打包到數組中,然後返回該數組:

function getAnswers($id_question) 
{ 
    $sql = 'SELECT * FROM answers WHERE question_id = '. $id_question; 

    $this->db->query($sql); 
    $data = array(); 
    while ($answers = $this->db->fetchAssoc()) 
    { 
     $data[] = $answers; 
    } 

    return $data; 
}