流程CSV进入阵列列标题密钥 [英] Process CSV Into Array With Column Headings For Key

查看:118
本文介绍了流程CSV进入阵列列标题密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含字段名的第一行的CSV。示例数据...

 制作,型号,注意
雪佛兰,1500,装
雪佛兰,2500,
雪佛兰,,装

我需要的键 - 值对的数组,其中关键字名称是列标题格式我的数据。我想这将是这样为行1:

  $阵列= [
    制作=> 雪佛兰,
    模式=> 1500,
    注=> 装
];

...第2行...

  $阵列= [
    制作=> 雪佛兰,
    模式=> 1500,
    注=>
];

...第3行...

  $阵列= [
    制作=> 雪佛兰,
    模式=> ,
    注=> 装
];

我不知道如何做到这一点以外的静态 - 问题是与它们相关的数据的列可以从一个文件更改为重新安排下...列,删除或添加

您的想法是多AP preciated。


解决方案

  $ ALL_ROWS =阵列();
$头= NULL;
而($行= fgetcsv($文件)){
    如果($头=== NULL){
        $标题= $行;
        继续;
    }
    $ ALL_ROWS [] = array_combine($标题,$行);
}

 的print_r($ ALL_ROWS);

I have a CSV with the first row containing the field names. Example data is...

"Make","Model","Note"
"Chevy","1500","loaded"
"Chevy","2500",""
"Chevy","","loaded"

I need my data formatted in an array of key-value pairs where the key name is the column heading. I guess it would something like this for row 1:

$array = [
    "Make" => "Chevy",
    "Model" => "1500",
    "Note" => "loaded"
];

...row 2...

$array = [
    "Make" => "Chevy",
    "Model" => "1500",
    "Note" => ""
];

...and row 3...

$array = [
    "Make" => "Chevy",
    "Model" => "",
    "Note" => "loaded"
];

I'm not sure how to do this other than statically - problem is the columns with their associated data could change from one file to the next... columns rearranged, dropped, or added.

You ideas are much appreciated.

解决方案

$all_rows = array();
$header = null;
while ($row = fgetcsv($file)) {
    if ($header === null) {
        $header = $row;
        continue;
    }
    $all_rows[] = array_combine($header, $row);
}

print_r($all_rows);

这篇关于流程CSV进入阵列列标题密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆