0

I'm basically wondering how to get specific rows from a csv file (lets say the file has 5000 rows I want to get the values of the second column from rows 3023 - 3311). Upon obtaining these column values I want to put them into a php array.

What I've tried so far:

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

But that only returns one single row and I need to return around 200 and put them into an array. Any help is greatly appreciated!

1 Answer 1

1

You're pretty close. You don't need to run a for loop inside of your while loop. You can use something like this:

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

In the above example, my array contains values from the second column of rows 50 to 100. Change the parameters to fit your criteria.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.