我的处理脚本有问题。我希望在一个csv文件中最多允许两个重复的ip地址,以防止一些垃圾邮件,并考虑到用户可能在填写表格时出错。我似乎无法在脚本中正确引用$ip变量,或者可能完全缺少一些内容。以下是迄今为止的代码片段:
<?php
#VARIABLE DECLARATIONS (filename and post vars) GO HERE
$counter = 0;
if (file_exists($filename))
{
$file = fopen($filename, "a");
while($data = fgetcsv($filename)){
if(isset($data[$ip])){
$counter++;
continue;
if((isset($data[$ip])){
$counter++;
if($counter == 2){
echo "";
}
}
}
}
##file write goes here
}
?>
如有任何帮助,将不胜感激
Jim
您必须首先读取数组中的所有元素,并且只有在准备好每个IP地址的出现次数后,才能继续写入文件(单独的文件可能是?)。
您可以首先准备一个数组,其中包含IP索引和与IP对应的所有行作为该键的值属性。这是可以做到的-
$csvArray = str_getcsv(file_get_contents('myCSVFile.csv'));
foreach($csvArray as $eachRow)
{
//prepare IP indexed array with every detail row as an attribute of the corresponding IP key.
$properlyFormattedArray[$eachRow[5]][] = $eachRow;
}
你会得到这样的数组-
Array(['92.27.21.171'] =>
[0] => Array("Mr","Test","davis","07972889989","01159174767","92.27.21.171"),
[1] => Array("Mr","bob","jones","07998998008","01159174767","92.27.21.171"),
...
['92.27.21.172'] => ...
)
一旦有了这个数组,只需在上面循环,每个IP最多只能写入2行。
foreach($properlyFormattedArray as $ip => $details)
{
$count = 0;
foreach($details as $eachDetail)
{
if($count<2)
{
//write $eachDetail into file
$count++;
}
}
}
但是,在这种情况下,数据的顺序(与输入文件相比)将被更改,重复的数据将被写入csv文件中的连续行中(不确定您是否同意)。