简体   繁体   中英

Getting all values of $row in csv file

I am trying this simple CSV file:

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:

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

The meaning is to get all values from A to I, not only the first one. 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 :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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