你好我在重写文件时遇到了问题:
static function Remove($plate){
$_parkedlist=parking::Read();
$_remove = false;
$_stillparkedlist = array();
foreach($_parkedlist as $_car){
if($_car[0] == $plate){
$_firsttime = $_car[1];
$_now = date('Y-m-d H:i:s');
$_timelapse = strtotime($_now) - strtotime($_firsttime);
$_topay = $_timelapse * 10;
echo "$_topay <br>";
$_remove = true;
} else {
$_stillparkedlist [] = $_car;
}
}
if ($_remove == true){
$mifile = fopen('parked.txt',"w");
foreach($_stillparkedlist as $_car){
if($_car[0]!=""){
$_line = $_car[0]."=>".$_car[1]."\n";
fwrite($mifile,$_line);
}
}
fclose($mifile);
}
}
原始文件是这样的:
234FSC=>2016-09-07 17:06:23
JAG823=>2016-09-07 17:06:15
706KHB=>2016-09-07 17:06:15
980GHB=>2016-09-07 17:06:15
我第一次删除它会添加空格(删除706KHB)
234FSC=>2016-09-07 17:06:23
JAG823=>2016-09-07 17:06:15
980GHB=>2016-09-07 17:06:15
如果我再次删除它会开始显示&#34;注意:未定义的偏移:1在... \ parking.php&#34;并且文件看起来像这样
234FSC=>2016-09-07 17:06:23
=>
JAG823=>2016-09-07 17:06:15
=>
980GHB=>2016-09-07 17:06:15
=>
我已经尝试了所有我能找到的但是这仍然发生在if($ _ car [0]!=&#34;&#34;)和isset($ _ car [0]!)
如何在没有此错误的情况下重写?
答案 0 :(得分:1)
我会假设从文件读取每一行,并且已经附加了换行符。
所以当你执行这一行
时$_line = $_car[0]."=>".$_car[1]."\n";
它正在添加另一个新行,所以改为
$_line = $_car[0]."=>".$_car[1];
所以你没有添加另一个换行符
答案 1 :(得分:0)
正在发生的事情是fwrite
已添加了PHP_EOL
,因此请删除额外的"\n"
但是也许您应该重组数组以使事情更容易:
static function Remove($plate){
$data = parking::Read();
// restructuring happens here.
foreach($data as $car){
$list[$car[0]] = $car[1];
}
foreach($list as $key => $val){
if($key == $plate){
$now = date('Y-m-d H:i:s');
$elapsed = strtotime($now) - strtotime($val);
$price = $elapsed * 10;
echo $price;
unset($list[$key]); // *poof*, removed the found car from the list.
break;
}
}
// if the new generated list is smaller then the original one, update.
if(sizeof($list) != sizeof($data)){
$fh = fopen('parked.txt',"w");
foreach($list as $key => $val){
fwrite($fh,"$key=>$plate");
}
fclose($fh);
}
}
此代码还有一个怪癖,它会自动删除重复的条目。