2012-01-23 4 views
0

Когда интерпретатор достигает $ pDB-> AddLine (5, «Test»), он перестает отвечать! Он возвращает следующую ошибку: «Неустранимая ошибка: максимальное время выполнения 30 секунд превышено ... в строке 21« Я что-то упустил? Должен ли я использовать array_push() вместо этого?Добавление элемента в массив

<?php 
    class pDb{ 
     protected $m_pArray; 
     public function __construct($arr){ 
      $this->m_pArray = $arr; 
     } 
     public function RemoveLine($index){ // Todo 
     } 
     public function ReplaceLine($index,$input){ 
      if(!$this->m_pArray)return -1; 
      $temp = array(); 
      for($i=0;$i<count($this->m_pArray);$i++){ 
       ($i == $index) ? $temp[$i] = $input : $temp[$i] = $this->m_pArray[$i]; 
      } 
      $this->m_pArray = $temp; 
     } 
     public function AddLine($index,$input){ 
      if(!$this->m_pArray)return -1; 
      $temp = array(); 
      for($i=0;$i<count($this->m_pArray);$i++){ 
       if($i == $index) { $temp[$i] = $input;$i = $i-1; }else{ $temp[$i] = $this->m_pArray[$i]; } 
      } 
      $this->m_pArray = $temp; 
     } 
     public function Get(){ if($this->m_pArray)return $this->m_pArray; return null;} 
     public function GetLine($i){ if($this->m_pArray)return $this->m_pArray[$i]; return null;} 
    } 

    $file = file("db.ini"); 
    for($i=0;$i<count($file);$i++){ 
     echo $i.": | ".$file[$i]."<br/>"; 
    } 

    echo "<br/>===================================================================================================================<br/><br/>"; 

    $pDB = new Pdb($file); 
    #$pDB->ReplaceLine(5,"Test"); // Works!!! 
    $pDB->AddLine(5,"Test"); // Crash!!! 
    for($i=0;$i<count($pDB->Get());$i++){ 
     echo $i.": | ".$pDB->GetLine($i)."<br/>"; 
    } 
?> 

Fix: Изменить

for($i=0;$i<count($this->m_pArray);$i++){ 
       if($i == $index) { $temp[$i] = $input;$i = $i-1; }else{ $temp[$i] = $this->m_pArray[$i]; } 
      } 

в

 $done=0; 
     for($i=0;$i<count($this->m_pArray)+1;$i++){ 
      if($i == $index && $done!=1){ $temp[$index] = $input; $done=1;}elseif($done == 1){ $temp[$i] = $this->m_pArray[$i-1]; }else{ $temp[$i] = $this->m_pArray[$i]; } 
     } 

ответ

4

Рассмотрим код ...

for($i=0;$i<count($this->m_pArray);$i++) { 
    if($i == $index) { 
    $temp[$i] = $input; 
    $i = $i-1; 
    } else { 
    $temp[$i] = $this->m_pArray[$i]; 
    } 
} 

Если $i == $index, то вы быстро вычесть одну из $i, и снова пройдите по петле. Это добавляет один к $i, что делает его равным $index, и вы попадаете в тот же случай - навсегда! Вам нужно либо связать условие цикла с чем-то, что вы меняете в ветке if (т. Е. $temp), либо полностью изменить логику здесь.

+0

Вы правы! Не могу поверить, что я пропустил это! –

1

Мне кажется, что последнее утверждение в этой линии в течение-петли «AddLine» проблема:

if($i == $index) { $temp[$i] = $input;$i = $i-1; } 

Как только $ я достигает 5 ($ индекса от вызова функции), вы всегда уменьшаете значение $ i, только чтобы оно снова увеличивалось по контуру, поэтому никогда не продолжалось. Бесконечный цикл -> тайм-аут.

Смежные вопросы