[英]Adding an item into an array
当解释器到达$ pDB-> AddLine(5,“ Test”)时,它将停止响应! 它返回以下错误“致命错误:在第21行的...中超过30秒的最大执行时间”我是否缺少某些内容? 我应该改用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]; }
}
考虑你的代码...
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
),或者在此处完全更改逻辑。
在我看来,“ AddLine”的for循环中这一行的最后一条语句是问题所在:
if($i == $index) { $temp[$i] = $input;$i = $i-1; }
一旦$ i达到5(函数调用中的$ index),您总是会减少$ i,只是让它在循环中再次增加,因此永远不会继续进行。 无限循环->超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.