从CSV解析时,PHP关联阵列的第一键会返回未定义的索引



我在从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);

现在$colors返回:

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

但是,如果我尝试访问任何颜色的ID

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

如果我可以循环浏览颜色,我可以像这样访问ID

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

但是为什么我无法直接访问$colors[0]["ID"]

谢谢

我也有同样的问题。问题是Excel在文档中的第一个单元格中添加了一个隐藏的字符,用于编码UTF-8 BOM。

我可以在运行时看到这一点:

var_dump(json_encode($array));

这将返回:

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

要删除 ufeff字符,我做到了:

$header = preg_replace('/[x00-x1Fx80-xFF]/', '', $header);

在这种情况下,那将是:

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

这对我有用!

header = preg_replace('/[ x00- x1f x80- xff]/','',$ header(;

最新更新