简体   繁体   English

使用get_file_contents()创建数组

[英]Using get_file_contents() to make an array

I am trying to upload a CSV file and get it's contents into an array, but I am getting this an error: (Multiples of this error on each line after 10) 我正在尝试上传CSV文件并将其内容存储到数组中,但出现此错误:(此错误的倍数在10之后的每一行)

Notice: Undefined offset: 1 in C:\xampp\htdocs\amazon\upload_file.php on line 10

Below is a sample of my code: 以下是我的代码示例:

if ($handle = file_get_contents($_FILES["file"]["tmp_name"])) {

$data = array();

while ($csv = array(file_get_contents($_FILES["file"]["tmp_name"]))) {
    $data = array(
        'order-id' => $csv[0],
        'order-item-id' => $csv[1], //This is line 10.
        'purchase-date' => $csv[2],
        'payments-date' => $csv[3],

file() opens puts each as an array element. file()打开后,将每个元素都放置为数组元素。 fgetcsv() and its family of functions are very useful when dealing with csv files. 在处理csv文件时, fgetcsv()及其功能系列非常有用。

Your code array(file_get_contents($_FILES["file"]["tmp_name"])) will only ever have one element because file_get_contents returns a string. 您的代码array(file_get_contents($_FILES["file"]["tmp_name"]))仅包含一个元素,因为file_get_contents返回一个字符串。

This issue comes if your file has only one line. 如果您的文件只有一行,则会出现此问题。

I guess you need to do this. 我想您需要这样做。

$row = explode(",", $csv[0]);
$data = array(
    'order-id' => $fileArray[0],
    'order-item-id' => $row[1], //This is line 10.
    'purchase-date' => $row[2],
    'payments-date' => $row[3]
);

Also, you can use functions like fgetcsv() to parse your CSV file. 另外,您可以使用fgetcsv()类的函数来解析CSV文件。

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

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