【问题标题】:Read CSV into Two Dimensional Array using First Line as Keys [duplicate]使用第一行作为键将 CSV 读入二维数组 [重复]
【发布时间】:2018-03-26 18:57:41
【问题描述】:

我正在尝试读取 CSV 文件,格式为:

titleA,titleB,titleC

data1A,data1B,data1C

data2A,data2B,data3C

预期的输出是:

Array
(
[0] => Array
(
[titleA] => data1A
[titleB] => data1B
[titleC] => data1C
)

[1] => Array
(
[titleA] => data2A
[titleB] => data2B
[titleC] => data2C
)

我尝试使用我在这里找到的东西:

if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$twoDarray[] = $data;
}
fclose($handle);
}

但它显示 1 个包含所有标题的数组和其他 2 个包含数据的数组。

【问题讨论】:

    标签: php arrays csv dimensional


    【解决方案1】:

    您想读取第一行并将其用作键并组合:

    if (($handle = fopen($filename, "r")) !== FALSE) {    
        $titles = fgetcsv($handle, 1000);
    
        while (($data = fgetcsv($handle, 1000)) !== FALSE) {
            $twoDarray[] = array_combine($titles, $data);
        }
        fclose($handle);
    }
    

    【讨论】:

      【解决方案2】:

      您可以将第一个作为标题,然后将其与每一行结合起来。

      $heading = array();
      $heading_check =1;
      if (($handle = fopen($filename, "r")) !== FALSE) {
          while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
              if($heading_check){
                  $heading = $data;
                  $heading_check=0;
                  continue;
              }
      
              $twoDarray[] = array_combine($heading,$data);
          }
      fclose($handle);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-03
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 2011-08-12
        • 2019-03-29
        • 2010-11-29
        • 2014-04-23
        相关资源
        最近更新 更多