如何将fgetscsv与csv文件一起使用PHP将文件解析为数组
ok so ive been trying to get this to work for hours now and cant figure it out. Ive got a csv file in the format of
item 1, item 1 stuff
item 2, item 2 stuff
item 3, item 3 stuff
item 4, item 4 stuff
and im trying to parse it into an array using fgetscsv.
$file = fopen('test.csv', 'r');
while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
print_r($MyCSVArray);
}
fclose($file);
I would really rather parse it into an associative array so i can index it like so
MyCSVArray[item 1]
which would output
item 1 stuff
However the problem I am having is that since there isnt a comma after every value it groups item 1 stuff with item 2 like so
MyCSVArray[0] = item 1
MyCSVArray[1] = item 1 stuff item 2
MyCSVArray[2] = item 2 stuff item 3
Maybe I dont understand csv files or the csv function, but I really need this to work the way I want and dont understand how to make it work and am about to smash my face into my keyboard.
好吧所以我一直试图让它工作几个小时,现在无法弄明白。 我有一个csv文件的格式为 p>
item 1,item 1 stuff
item 2,item 2 stuff
item 3,item 3 stuff
item 4,item 4 stuff
code> pre>
我试图使用fgetscsv将其解析为数组。 p>
$ file = fopen('test.csv','r');
while(($ MyCSVArray = fgetcsv($ file))!== FALSE){
print_r($ MyCSVArray);
}
nclclose($ file);
code> pre>
我真的宁愿把它解析为关联数组,所以我可以 索引就像这样 p>
MyCSVArray [item 1]
code> pre>
将输出 p>
\ n
item 1 stuff
code> pre>
但是我遇到的问题是,因为在每个值之后都没有逗号,所以它将项目1的内容与项目组合在一起 2喜欢这样 p>
MyCSVArray [0] = item 1
MyCSVArray [1] = item 1 stuff item 2
MyCSVArray [2] = item 2 stuff item 3
代码> pre>
也许我不理解csv文件或csv函数,但我真的需要这个以我想要的方式工作,不明白如何让它工作,我即将粉碎我的脸 进入我的键盘。 p>
div>
Just read the data like you are and set the value into a new associative array as desired
$new_array = array()
$file = fopen('test.csv', 'r');
while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
$new_array[$MyCSVArray[0]] = $MyCSVArray[1];
}
fclose($file);
var_dump($new_array);
To the second part of your problem, it seems like you might not have proper end of line characters in your file if items from the next row are being grouped with the items from previous row.