简体   繁体   English

从CSV文件读取时获取空值

[英]getting null values while reading from csv file

I have a csv file which has a word for each row like this 我有一个csv文件,每个行都有一个这样的单词

word1
word2
word3

And have the following code to read the data: 并具有以下代码来读取数据:

$arr = array();
$fh = fopen('path/to/file', 'r');
while (($rows = fgetcsv($fh)) !== false) {
 print_r($rows);
 if (!in_array($rows[0], $arr))
  $arr[] = "'".trim($rows[0])."'";
}
fclose($fh);
print_r($arr);

The problem is im getting empty strings/null for $rows[0] and im quite sure the data is there. 问题是我获得了$ rows [0]的空字符串/空值,并且非常确定数据在那里。

Array ( [0] => )
Array ( [0] => )
Array ( [0] => )

Array ( [0] => '' [1] => '' [2] => '' [3] => '' )

Any help would be greatly appreciated. 任何帮助将不胜感激。

You're trying to read the words into an array? 您正在尝试将单词读入数组吗? Replace all that with just: 将所有内容替换为:

$arr = file('/path/to/file');
print_r($arr);

Cannot reproduce. 无法复制。 I'm assuming there is something wrong with your file format. 我假设您的文件格式有问题。 Most likely there is an empty line on top (which I'm not quite sure, but might fail the !== false test). 最有可能在顶部有一个空行(我不太确定,但是可能会通过!== false测试)。

Better try: 更好的尝试:

$arr = array_map("str_getcsv", file("words.csv"));
print_r($arr);

And if you need to re-add the quotes, do a separate loop. 如果您需要重新添加引号,请执行一个单独的循环。

The file reading part has already been answered, but about your loop to add the quotes, you could use array_walk() : 文件读取部分已经回答,但是关于添加引号的循环,可以使用array_walk()

function add_quotes(&$item)
{
    $item = "'" . $item . "'";
}

array_walk($arr, "add_quotes");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM