在 PHP 中使用 fgetcsv 函数时,在 CSV 数据中保留前导零

Keep leading zeros in CSV data when using fgetcsv function in PHP

经过几个小时的研究,我在找到解决方案时遇到了一些麻烦。我的数据库中有一列名为 LAST4 的数据。一些数据示例“0564”、“0002”等...当我 运行 脚本时,它会删除“0564”的前导零并将其转换为“564”或“0002”结果为“2” .如何保存带有前导零的数据?如有任何帮助,我们将不胜感激!

    //CSV Database 
    $handle = fopen("/home/file/path.csv", "r");

    $count = 0;
    $members = array();

    while(($data = fgetcsv($handle, 10000, ",")) !== FALSE) {

      if ($count >= 1) { 

         /* Convert Date of Birth to Timestamp with Function */   
         $dateofbirth = date("Y-m-d", strtotime($data[2]));  

         /* Convert Layoff Date to Timestamp with Function */   
         $layoffdate = date("Y-m-d H:i:s", strtotime($data[5])); 


        /* Build Variables for User Access Account */
        $userlogin = $dateofbirth . '-' . $data[3];
        $userpw = $data[1] . '' . $data[3];
        $userem = $dateofbirth . '-' . $data[3] . '@example.org';

        /* Creates a New User For User Access */
         $userDatas[] = array(
          'user_login' => $userlogin,
          'first_name' => $data[0],
          'last_name' => $data[1],
          'user_pass' => $userpw,
          'user_email' => $userem,
          'user_url' => '',
          'role' => 'member'
         );

         /* Creates New Member Entry in Table */
         $members[] = array(  
         'FIRST_NAME' => $data[0],
         'LAST_NAME' => $data[1],
         'DOB' => $dateofbirth, 
         'LAST4' => $data[3],
         'FLAG' => $data[4],
         'LAID_OFF_DATE' => $layoffdate, 
         'PHONE_NUMBER' => $data[6]
         ); 

       }

       $count++;

首先尝试将其转换为字符串。所以代替:

'LAST4' => $data[3],

您可以使用:

'LAST4' => (string)$data[3],

与您希望它发生的其他值类似。