duandie0921 2011-04-22 19:17
浏览 89
已采纳

PHP无法重命名数组键

I am reading hundreds of CSVs to import into a DB.

Some of the column names contain the same data but have different names across all the files.

For example, one file will say Phone where the other says EveningPhone...both contain the same data, different names.

I am trying to rename everything to EveningPhone because I had most of the code done when i realized there were different header names in different files. Too lazy to replace all i guess..

I am creating an assoc array to match the data then off to the db it goes..

The problem is I cannot get the keys to rename to one convention. Here is the function where it happens:

public function readCSV($file) {
    /**
     * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS
     */

    // Read the first line to get the headers
    $headers = fgetcsv($file);


    if (!array_key_exists('EveningPhone', $headers)) {
        if (array_key_exists('Phone', $headers)) {
            $headers['EveningPhone'] = $headers['Phone'];
            unset($headers['Phone']);
        } else {
            die("other");
        }
    }

    format::neat_r($headers);   // basically print_r but adds a new line to read it easier...
    die();

The array is returned before and after as this:

LeadID

AddDate LastName FirstName Address City State ZipCode LeadLocator Phone Email Sex Comments

At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number..

Anybody have any ideas?

  • 写回答

2条回答 默认 最新

  • dongtiaobeng7901 2011-04-22 19:33
    关注

    fgetcsv does not return an associative array. It will return an array with the data as values so you should be using in_array or array_search (when you need the key). The code that reads the actual data is probably using array_combine to build an associative array using the header.

    public function readCSV($file) {
        /**
         * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS
         */
    
        // Read the first line to get the headers
        $headers = fgetcsv($file);
    
    
        if (!in_array('EveningPhone', $headers)) {
            if ($phoneKey = array_search('Phone', $headers)) {
                $headers[$phoneKey] = 'EveningPhone';
            } else {
                die("other");
            }
        }
    
        format::neat_r($headers);   // basically print_r but adds a new line to read it easier...
        die();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了