“写入到文本文件”在单击第一个项目时不起作用


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):

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

我不知道为什么会这样,所以我希望一双新鲜的眼睛可以指出一些明显的东西…我有一种感觉,它与if($strpos= strpos(file_get_contents($file), $state)){中的if语句行有关,但我不能确定。这似乎是一个奇怪的问题,代码工作100%正确的一切,但你点击的第一个状态。我知道这是第一种状态,只是因为我已经用不同的状态作为第一种尝试了很多次。

有什么想法或建议吗?

注意,当您使用strpos查看string是否存在时,您应该检查boolean:

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

否则,当你的strpos返回0时,你将得到假阴性。

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

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