2013-12-18 79 views
0

因此,我從數據庫中獲取對象,並且希望將ID和點放在數組中。 而且每次getIscorrect等於真正的id的值必須增加1php爲數組添加鍵值

$answers = array(); 
    $return = $this->_quizMapper->getAll(); 
    foreach($return as $answer){ 
     if($answer->getIscorrect() == true){ 
      if(!($answers[$answer->getID()])){ 
       $answers[$answer->getID()] = 1; 
      } 
      else{ 
       $newPoints = $answers[$answer->getID()] + 1; 
       $answers[$answer->getID()] = $newPoints; 
      } 
     } 
    } 

,但我不斷收到錯誤:PHP公告:未定義的索引:在此行if(!($answers[$answer->getID()])){

+0

'var_dump($ answer-> getID());'看看它是你期望的。 –

回答

0

將其更改爲if (!isset($answers[$answer->getID()]))

這將抑制通知。

+0

你是最快的! –

0

這是因爲沒有定義的關鍵。

你應該用的是:

if(!isset($answers[$answer->getID()]) || !($answers[$answer->getID()])){ 
0

更改您的代碼是:

$answers = array(); 
$return = $this->_quizMapper->getAll(); 
foreach($return as $answer) 
{ 
    if($answer->getIscorrect() == true) 
    { 
     if(!isset($answers[$answer->getID()])) 
     { 
      $answers[$answer->getID()] = 1; 
     } 
     else 
     { 
      $newPoints = $answers[$answer->getID()] + 1; 
      $answers[$answer->getID()] = $newPoints; 
     } 
    } 
} 

您必須使用方法isset()以檢查當前鍵數組中存在。