0

我几乎不好意思问这个,但我已经尝试完成这个任务几个小时了。如果没有彻底掌握fopenfgetcsv 函数,我有点迷茫。我发现的每个示例都不太适合我。

我正在寻找一种将 CSV 文件的每一行加载到一个数组中的方法。例如,如果这是我的 CSV 文件:

Apple,Banana,Orange
Kiwi,Watermelon,Pineapple
Dog,Cat,Bird

那么这将是我的数组:

Array
(
    [0] => Apple,Banana,Orange
    [1] => Kiwi,Watermelon,Pineapple
    [2] => Dog,Cat,Bird
)

我会很感激任何提示。谢谢!:)


仅供参考,这是我目前所拥有的:

$list = '../reports/apples.csv';

$csvfile = fopen($list,'rb');
while(!feof($csvfile)) {
$listofthings[] = fgetcsv($csvfile);
}
fclose($csvfile);

print_r($listofthings);

但是,当我宁愿只拥有一个大数组时,这会产生如下的多维数组。

Array
(
    [0] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Orange
        )

    [1] => Array
        (
            [0] => Kiwi
            [1] => Watermelon
            [2] => Pineapple
        )

    [2] => Array
        (
            [0] => Dog
            [1] => Cat
            [2] => Bird
        )
)
4

3 回答 3

2

如果要按行拆分文件,请使用file.

$newArray = file('/path/to/file.csv');

如果您希望每个以逗号分隔的值作为数组的一个元素,请使用file_get_contents逗号并以逗号分隔。

$contents = file_get_contents('/path/to/file.csv');
$newArray = explode(',', $contents); 
于 2013-02-23T04:29:53.593 回答
1

您可以explode按照 Nicholas 的建议阅读文件,也可以使用以下命令一次性完成所有操作file

$lines = file('/path/to/file.csv');
于 2013-02-23T04:36:41.847 回答
0

正在找这个??

$mytext = "Apple,Banana,Orange
Kiwi,Watermelon,Pineapple
Dog,Cat,Bird";

$line_explode = explode("\n", $mytext);
$comma_explode = array();
foreach ($line_explode as $line) {
  $comma_explode[] = explode(",", $line);
}

print_r($comma_explode);

输出

Array
(
    [0] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Orange
        )

    [1] => Array
        (
            [0] => Kiwi
            [1] => Watermelon
            [2] => Pineapple
        )

    [2] => Array
        (
            [0] => Dog
            [1] => Cat
            [2] => Bird
        )

)
于 2013-02-23T04:38:39.730 回答