doudou1438 2013-10-04 18:51
浏览 57
已采纳

如何将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.

  • 写回答

1条回答 默认 最新

  • dongxian7489 2013-10-04 18:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)