du6333137 2016-08-22 14:57
浏览 36
已采纳

PHP str_getcsv不会分隔索引1和2中的元素

I'm importing a CSV and creating a 2D array with it. The problem is that in the indexes 1 and 2 the function doesn't recognize the separator "," so every array is ok but the ones in the second and third position.

I tried with multiple files, multiple software (LibreOffice, Google Spreadsheet) and it has always the same problem.

This is the code:

$dbLocation = 'upload/db.csv';

$paramStrGetCsv = array(",", '"', "\\");
$db = array_map('str_getcsv', file($dbLocation), $paramStrGetCsv);

print "<pre>";
print_r($db);
print "</pre>";

This is the array $db:

Array
(
    [0] => Array
        (
            [0] => email
            [1] => name
            [2] => surname
            [3] => birthdate
        )

    [1] => Array
        (
            [0] => red@email.com,red,qwer,1990-06-01
        )

    [2] => Array
        (
            [0] => blue@gmail.com,blue,poiu,1990-01-01
        )

    [3] => Array
        (
            [0] => green@yahoo.com
            [1] => green
            [2] => yuiop
            [3] => 1980-01-01
        )

    [4] => Array
        (
            [0] => purple@gmail.com
            [1] => purple
            [2] => zxcvbn
            [3] => 1975-01-01
        )

    [5] => Array
        (
            [0] => yellow@gmail.com
            [1] => yellow
            [2] => vbnm
            [3] => 1970-01-01
        )
)

This is the csv file:

email,name,surname,birthdate
red@email.com,red,qwer,1990-06-01
blue@gmail.com,blue,poiu,1990-01-01
green@yahoo.com,green,yuiop,1980-01-01
purple@gmail.com,purple,zxcvbn,1975-01-01
yellow@gmail.com,yellow,vbnm,1970-01-01

Thank you, Federico.

  • 写回答

1条回答 默认 最新

  • douhuigang9550 2016-08-22 15:16
    关注

    So here's your problem:

    $db = array_map('str_getcsv', file($dbLocation), $paramStrGetCsv);
    

    First entry will run function str_getcsv("email,name,surname,birthdate", ",")

    Second will run str_getcsv(red@email.com,red,qwer,1990-06-01, "\"")

    and generally array map maps mutliple arrays using a single function which accepts multiple arguments, so it will try to use both the file and the $paramStrGetCsv to do the mapping. Instead do this:

    $db = array_map(function ($ln) { return str_getcsv($ln,",", '"', "\\"); }, file($dbLocation));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵