写入文本文件不适用于单击的第一个项目

Write to text file will not work with the first item clicked

我有一个奇怪的问题,我不知道哪里出了问题。我正在编写美国的交互式地图。用户点击一个状态,点击记录在一个文本文件中。然后点击总数显示在地图上。它基本上是一个完整数据库的快速解决方法。

代码有效。每次单击状态时,它都会添加到文本文件中。如果该状态尚不存在,则为其创建一个条目。如果是,则点击次数会简单更新。这是文件:

<?php 
    // get the input from AJAX
    @$state = $_GET['state'];
    // get the txt file where all of the states are 
    $file = 'state_count.txt';
        //if state_count.txt exists 
        if($fopen = fopen($file, 'c')){ 
            //open it and check if the name of the state is recorded or not 
            if($strpos= strpos(file_get_contents($file), $state)){
                //if so, add 1 to the value after the state's name
                // in the formate State:#
                //cut the text file into an array by lines 
                $lines = file($file);
                //foreach line, parse the text 
                foreach($lines as $l => $k){ 
                    // create a new array $strings where each key is the STATE NAME and each value is the # of clicks 
                    $strings[explode(':', $k)[0]] = explode(':', $k)[1];
                } 
                // add 1 to the # of clicks for the state that was clicked
                $strings[$state] = $strings[$state]+1;  
                // move cursor to the end of the state's name and add 1 to accomodate the : 
                fseek($fopen, $strpos+strlen($state)+1, SEEK_SET); 
                // overwrite number in file
                fwrite($fopen, $strings[$state]); 

                // debug print($strings[$state]);

            }
            //if not, add it with the value 1
            else{ 
                file_put_contents($file, $state.":1\n", FILE_APPEND); 
            } 
        }   
        //if does not exist
        else{ 
            die('Cannot create or open file.'); 
        } 

?>

我遇到的问题是代码适用于所有状态,除了被单击的第一个状态(即文本文件为空,用户单击一个状态,该状态是第一个状态)。在这种情况下,它永远不会更新最初的点击状态,它只是为它创建一堆单独的条目。它最终看起来像这样(假设我先点击了宾夕法尼亚州):

Pennsylvania:1
Pennsylvania:1
Utah:1
Colorado:1
Kansas:1
Nebraska:1
Wyoming:1
Indiana:1
Ohio:3
Virginia:1
West Virginia:2
Kentucky:8
Tennessee:1
Georgia:1
Alabama:2
Mississippi:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1

我不确定为什么要这样做,所以我希望一双新鲜的眼睛能指出一些明显的东西......我觉得它与 [=12 中的 if 语句行有关=],但我不能确定。对于除了您单击的第一个状态之外的所有内容,代码都能 100% 正确地工作,这似乎是一个奇怪的问题。我知道它是第一个状态只是因为我已经用不同的状态作为第一个尝试了很多次。

有什么想法或建议吗?

请注意,当您使用 strpos 查看字符串是否存在时,您应该检查布尔值:

if (strpos(....) !== false) { ... }

否则,当您的 strpos returns 0 与您的情况一样时,您将出现假阴性。

在您的代码中,您可以这样处理:

$strpos= strpos(file_get_contents($file), $state);
if ($strpos !== false) {...