简体   繁体   English

从csv文件php创建关联数组

[英]Creating an associative array from a csv file php

I'm trying to read a csv file and then store the first and the 21st column in an associative array such that the 1st column becomes the key and 21st column becomes the value. 我正在尝试读取一个csv文件,然后将第一列和第21列存储在关联数组中,以使第1列成为键,而第21列成为值。

Later I would want to pull records based on the "key". 稍后,我想根据“键”提取记录。 The PHP file containing the code is upload.php 包含代码的PHP文件是upload.php

$calls = array();
$file_handle = fopen($C1.".File.csv","r"); // $C1 is defined before.
 //Just appending something to the file name. This file exists. 
while (!feof($file_handle) ) {
    $line= fgetcsv($file_handle, 1024);
    $calls[$line[0]] = $line[20]; //Line 94 of this file

}
fclose($file_handle);
print_r($calls);

I get this error 我得到这个错误

Undefined offset: 20 in upload.php on line 94

Where am I going wrong. 我要去哪里错了。

The twentieth "column" in a zero-indexed array would be $line[19] 零索引数组中的第二十个“列”为$line[19]

update as per your comment (and subsequent edit): 根据您的评论进行更新(以及随后的修改):

The error is clearly pointing out at some point during the loop $line[20] is not set - If each line has a suitable number of columns then the only other reason I can think of is that there is an empty line at the end of the CSV file. 错误显然在未设置$line[20]循环期间的某个点指出-如果每行都有合适的列数,那么我能想到的唯一另一个原因是在该行的末尾有一个空行CSV文件。

Eg. 例如。

1.  foo, bar, baz
2.  a  , b  , c
3.                    <-- empty line as a result of carriage return

so... you want to check that trim($line)!='' before fgetcsv and/or as part of good error-handling check that the array's length is greater than the highest index you are trying to read. 所以...您想在fgetcsv之前检查trim($line)!=''和/或作为良好错误处理的一部分,检查数组的长度是否大于您尝试读取的最高索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM