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 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 VUE项目怎么运行,系统打不开