php - 使用 PHP 将单列从 CSV 转换为简单数组

标签 php arrays csv fgetcsv

我有一个 csv,在没有标题的单列中包含电子邮件列表。

很简单,他们是这样的:

example@123.com
email@somewhere.com
helloworld@email.org

...等等

其中有 30k。

我需要使用 PHP 将这个电子邮件列表转换为一个简单的数组。

我理解 fgetcsv() 的概念,但正如我们所知,它一次读取一行,所以我最终得到的是通过遍历我的 csv 而不是一个数组的多个数组。

我需要这个:

Array
(
    [0] => example@123.com
    [1] => email@somewhere.com
    [2] => helloworld@email.org
)

我得到的是这样的:

Array
(
    [0] => example@123.com
)

Array
(
    [0] => email@somewhere.com
)

Array
(
    [0] => helloworld@email.org
)

这是我的代码:

if (($file = fopen("emails.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($file)) !== FALSE) {
          // do stuff
    }

    echo '<pre>';
    print_r($data);
    echo '</pre>';
    echo '<br/>';   

    fclose($file);  
}

是否有一种简单的方法可以使用 PHP 将整个 CSV 列简单地转换为数组?我一直在进行研究,但尚未找到解决方案。

最佳答案

如果您的文件中只有一列,您真的不需要使用 fgetcsv。您可以改用 fgets 函数 ( http://us2.php.net/manual/en/function.fgets.php )。此函数返回一个字符串,您可以像这样轻松地将其添加到数组中:

$emails = array();
if (($file = fopen("emails.csv", "r")) !== FALSE) {
    while (($email = fgets($file)) !== FALSE) {
         $emails[] = $email;
    }
    fclose($file);  
}

或者,如果您坚持使用 fgetcsv,您可以按如下方式更改代码:

$emails = array();
if (($file = fopen("emails.csv", "r")) !== FALSE) {
    while (($arr = fgetcsv($file)) !== FALSE) {
         $emails[] = $arr[0];
    }
    fclose($file);  
}

最后,我已经阅读但未亲自测试,stream_get_line 函数 ( http://www.php.net/manual/en/function.stream-get-line.php) 甚至比 fgets 更快。您可以在上面替换它。

关于php - 使用 PHP 将单列从 CSV 转换为简单数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824767/

相关文章:

ios - 在 Swift 中向数组添加元素

Python For 循环和 BeautifulSoup 结果转换为 CSV

php - % _ 在搜索表单中显示所有结果

C 动态分配速度问题

c# - 如何将Dictionary <int,long>转换为字符串数组/列表?

python - 如何将 csv 中的行插入到 postgres+python 中现有表中的特定列?

python - 如何使用子进程和 'cat'逐行读入数据?

php - 如何实现分页?

php重定向页面问题

php - ProcessWire foreach 循环显示每行 4 列