如何 return 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);
但是那只有 return 一行,我需要 return 大约 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 行的第二列中的值。更改参数以符合您的条件。
我基本上想知道如何从 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);
但是那只有 return 一行,我需要 return 大约 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 行的第二列中的值。更改参数以符合您的条件。