簡體   English   中英

如何從csv文件返回特定行並將其放入數組

[英]How to return specific rows from a csv file and put them into array

我基本上想知道如何從csv文件中獲取特定的行(可以說該文件有5000行,我想從3023-3311行中獲取第二列的值)。 獲得這些列值后,我想將它們放入php數組。

到目前為止,我已經嘗試過:

 $search = $this->uri->segment(3); // get the row number    
 $row1 = 0;

   if (($handle = fopen("Folder/Data.csv", "r")) !== FALSE)
    {
        while (($data1 = fgetcsv($handle, 1000, ",")) !== FALSE)
        {
            $num1 = count($data1); // number of data rows
            $row1++;
            for ($c=0; $c < $num1; $c++) {



                echo $data1[$c+1]; // to return second row


            }
        }
        fclose($handle);

但這只返回一行,我需要返回大約200行並將它們放入一個數組中。 任何幫助是極大的贊賞!

你很親密 您無需在while循環內運行for循環。 您可以使用如下形式:

$file = fopen('/path/to/file', 'r');

// Helps us keep tabs on the row we are on
$rowCount = 0;
// Array that stores all of our column values.  In this case, I'll be gathering 
// values from the second column
$secondColumnArray = array();
while(false !== ($rowData = fgetcsv($file))){
    if($rowCount >= 50 && $rowCount <= 100){
        array_push($secondColumnArray, $rowData[1]);
    }
    $rowCount = $rowCount + 1;
}

print_r($secondColumnArray);

fclose($file);

在上面的示例中,我的數組包含第50到100行第二列中的值。更改參數以符合您的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM