2012-01-23 96 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/>"; 
    } 
?> 

修复: 变化

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

在我看来,在这一行中的最后一条语句for循环的“AddLine”的问题是:

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

只要$ i达到5(从函数调用$指数),你总是减少$ i,只是让它在循环中再次增加,因此永远不会再继续。无限循环 - >超时。