简体   繁体   English

在csv文件中获取$ row的所有值

[英]Getting all values of $row in csv file

I am trying this simple CSV file: 我正在尝试这个简单的CSV文件:

A;23
B;24
C;25
D;26
E;123
F;243
G;180
H;55
I;243

The meaning is to get an array with all values of the first column. 含义是获取具有第一列的所有值的数组。 The code looks like this: 代码如下:

<?php

    function importData($file, $store_id) {

        $handle = fopen($file, "r");

        while ($row = fgetcsv($handle, 0, ";")) {
        $productIds = array($row[1]);
        var_dump($productIds);
        exit;

        }
        fclose($handle);
    }

    importData("/home/test.csv", 3);

?>

When I dump the information of $row[0] I get the following: 当我转储$row[0]的信息时,我得到以下信息:

array(1) {
  [0]=>
  string(1) "A"
}

The meaning is to get all values from A to I, not only the first one. 含义是将所有值从A到I,而不仅仅是第一个。 What would be necessary to apply to the code? 对该代码有什么要求?

Thanks for your collaborations 感谢您的合作

You're overwriting the array each time. 您每次都覆盖数组。 Instead initalize the array once, and then add elements using array_push() or using the square bracket syntax : 而是初始化一次数组,然后使用array_push()或使用方括号语法添加元素:

function importData($file, $store_id) {
    $productIds = array();

    $handle = fopen($file, "r");

    while ($row = fgetcsv($handle, 0, ";")) {
        // Append the value onto the array
        $productIds[] = $row[1];
    }
    fclose($handle);
    return $productIds;
}

$productIds = importData("/home/test.csv", 3);

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

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