doudang9147 2017-04-14 15:40
浏览 52

当从CSV解析时,php关联数组的第一个键返回未定义的索引

I am having trouble accessing the first index of an associative array when parsing from a csv.

CSV:

ID,COLOR
1,Red
2,Green 
3,Blue

PHP:

function associative_array_from_csv($csv)
{
    $rows   = array_map('str_getcsv', file($csv));
    $header = array_shift($rows);
    $array  = array();

    foreach($rows as $data) {
        $array[] = array_combine($header, $data);
    }

    return $array;
}

$colors = associative_array_from_csv($csv);

Now $colors returns:

[
    [
        "ID"    => "1",
        "COLOR" => "Red",
    ],
    [
        "ID"    => "2",
        "COLOR" => "Green ",
    ],
    [
        "ID"    => "3",
        "COLOR" => "Blue",
    ],
];

But if I try to access the ID of any color:

$colors[0]["ID"]    // returns undefined index: ID
$colors[0]["COLOR"] // returns "Red"

If I loop over the colors I can access the ID like so:

foreach($colors as $color) 
{ 
    print_r(reset($color)); // Prints the ID 
}

But why I can't access it directly like $colors[0]["ID"]?

Thanks

  • 写回答

1条回答 默认 最新

  • duanniubeng2265 2019-03-26 05:50
    关注

    I had the same issue. The problem was that Excel adds a hidden character to the first cell in the document, for encoding UTF-8 BOM.

    I could see this when running:

    var_dump(json_encode($array));
    

    This would return:

    string(312) "[{"\ufeffemail":"test@me.com","firstName":"import","lastName":"test"},{"\ufeffemail":"test@comcast.net","firstName":"import","lastName":"test"}]"
    

    To remove the \ufeff character, I did:

    $header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
    

    In this case, that would be:

    function associative_array_from_csv($csv)
    {
        $rows   = array_map('str_getcsv', file($csv));
        $header = array_shift($rows);
        $header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
        $array  = array();
    
        foreach($rows as $data) {
            $array[] = array_combine($header, $data);
        }
    
        return $array;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据