5

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

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

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

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

有什么想法或建议吗?

4

1 回答 1

5

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

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

否则,当您的 strpos 返回 0 时,您将得到假阴性,就像您的情况一样。

在您的代码中,您可以使用以下方法:

$strpos= strpos(file_get_contents($file), $state);
if ($strpos !== false) {...
于 2015-07-27T18:00:48.413 回答