php数组in_array奇怪

时间:2009-07-14 00:12:16

标签: php arrays

我所知道的所有语言都是php中最弱的...

我有一个脚本...它接受一个csv文件并用它做一些事情......非常简单。

我遇到的问题: in_array('username',$ headers)...返回null ... 而... print_r($ headers);显示用户名是csv中的第一个条目。

想法?我可能犯过的错误?

TIA

代码

/// Turn the string into an array
            $rows = explode("\n", $this->raw_data);

            /// First row includes headers
            $headers = $rows[0];
            $headers = explode($this->delimiter, $headers);

            /// Trim spaces from $headers
            $headers = array_map('trim', $headers);

            /// Check that there are no empty headers. This can happen if there are delimiters at the end of the file
            foreach($headers as $header){

                    if(!empty($header)){
                            $headers2[] = $header;
                    }
            }
            $headers = $headers2;

            if(! in_array('password', $headers)){
                    /// Add password column for generated passwords
                    $headers[] = 'password';
            }
            /// Add status column to the headers
            $headers[] = 'status';

            $this->headers = $headers;

            /// Check that at least username, name and email are provided in the headers
            if(!in_array('username', $headers) ||
               !in_array('name', $headers) ||
               !in_array('email', $headers)){

               echo "error\n";   
               return false;
            }

3 个答案:

答案 0 :(得分:2)

您可以使用内置的str_getcsv()功能。尝试用

替换$headers变量赋值
$headers = str_getcsv($rows[0], $this->delimiter);

然后找到你想要的值(列),并使用相同的$rows函数遍历str_getcsv()的其余部分,以获得所需的匹配项。

您可能希望使用file()函数来抓取由新行开头的数组中的文件。

答案 1 :(得分:0)

检查前三个函数in this list。您的问题可能源于多种原因。首先使用内置的CSV函数消除不必要的解析。

答案 2 :(得分:-1)

我没有看到将$ headers2设置为数组的代码。第二次赋值发生后,第一次赋值给该变量会丢失吗?