douqiao7958 2014-07-23 15:42
浏览 53
已采纳

如何在PHP中修剪数组中的空格

I'm trying to parse a CSV file and as part of it I would like to remove leading/trailing whitespace from all of my cells. Since it's a CSV file it's formatted like a 2D array. Initially I tried:

foreach($csv as $row){
    foreach($row as $cell){
        $cell = trim($cell);
    }
}

However the result was untrimmed.

Next I tried using array_map as suggested here.

$csv = array_map('trim', $csv);

This gave me back an array of empty rows. So I also tried

foreach($csv as $row){
    $row = array_map('trim', $row);
}

Which like my first attempt didn't change anything.

Here's the CSV data I'm using as my input:

First Name,Last Name,Contact Method,Phone, Email John,Doe,Email,1-XXX-XXX-XXXX, john@example.com Jane,Doe,Phone Call,1-XXX-XXX-XXXX,jane@example.com

In particular I was trying to get my script to trim the leading space in the last cell of the first row (" Email" => "Email").

  • 写回答

4条回答 默认 最新

  • duanjia2415 2014-07-23 15:48
    关注

    You are not modifying the original array when you do the trim. You should get the values by reference in the foreach loop.

    foreach($csv as &$row){
        foreach($row as &$cell){
            $cell = trim($cell);
        }
    }
    

    From the documentation:

    In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证