2015-08-07 14:18
浏览 179


I'm using this code to get an array from a csv file:

array_map('str_getcsv', 'file.csv')

But how do I set delimeter for str_getcsv() when using it in array_map function?

图片转代码服务由CSDN问答提供 功能建议

我正在使用此代码从csv文件中获取数组: < pre> array_map('str_getcsv','file.csv')

但是如何为 str_getcsv()在array_map函数中使用它时?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtz8044 2015-08-07 14:23

    If you need to attach additional parameters to a function that requires a callable the easiest way it to just pass in a wrapper function with your parameters pre-defined

    $array = array_map(function($d) {
        return str_getcsv($d, "\t");
    }, file("file.csv"));

    Alternatively you can pass in parameters using the use() syntax with the closure.

    $delimiter = "|";
    $array = array_map(function($d) use ($delimiter) {
        return str_getcsv($d, $delimiter);
    }, file("file.csv"));

    Another fun thing that can be done with this technique is create a function that returns functions with predefined values built in.

    function getDelimitedStringParser($delimiter, $enclosure, $escapeChar){
        return function ($str) use ($delimiter, $enclosure, $escapeChar) {
            return str_getcsv($str, $delimiter, $enclosure, $escapeChar);
    $fileData = array_map("trim", file("myfile.csv"));
    $csv = array_map(getDelimitedStringParser(",", '"', "\\"), $fileData);
    解决 无用
    打赏 举报

相关推荐 更多相似问题