2014-10-30 71 views
0

我遇到了处理脚本的问题。我想在csv文件中允许最多2个重复的IP地址,以防止一些垃圾邮件,并考虑到用户可能在填表时犯了一个错误。我似乎无法在脚本中正确引用$ ip变量,或者可能有一些我完全错过了。这里是代码片段迄今:允许2个重复的IP地址最大值php csv

<?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 
} 

?> 

任何帮助,将不胜感激,

吉姆

+0

当你的脚本开始工作时,它是否有空的csv文件,或者它已经有一些数据?你是从一个数组中读取csv文件还是从同一个csv文件读取数据(即你的脚本有效地从csv文件中删除多余的IP)? – 2014-10-30 11:29:38

+0

将会执行'continue'后的任何内容。 – Barmar 2014-10-30 11:34:06

+0

感谢您的回复,.csv文件已将文件中的数据包含标题,并且.csv文件在从相同的.csv文件读取后写入。 – Soxxxy 2014-10-30 11:36:48

回答

0

你必须先和你的后,才读阵列中的所有元素准备好每个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。

foreach($properlyFormattedArray as $ip => $details) 
{ 
    $count = 0; 
    foreach($details as $eachDetail) 
    { 
     if($count<2) 
     { 
      //write $eachDetail into file 
      $count++; 
     } 
    } 

} 

但是,在这种情况下,数据(与输入文件相比)的订单将被改变,重复的将被写入CSV文件连续行(不知道你会不会介意的它)。

+0

谢谢你的洞察和帮助,我会当我解决了问题后回复 – Soxxxy 2014-10-30 12:19:37

+0

好的,当然...... – 2014-10-30 12:35:16

+0

感谢您的帮助:文件正在写入,但它插入了两行。我只是希望它插入行,如果IP地址在文件中已经有一次,并且如果它已经在文件中已经驻留两次,则跳过它 – Soxxxy 2014-10-30 12:52:49