[英]Reading in .csv file PHP-ML
I am using php-ml and taking in a .csv file with 6 columns and thousands of lines, i want every 5th element (column) of each array to be saved in $samples.我正在使用 php-ml 并接收一个包含 6 列和数千行的 .csv 文件,我希望每个数组的每个第 5 个元素(列)都保存在 $samples 中。 I have tried the following which gives me the first element of each array.我尝试了以下方法,它为我提供了每个数组的第一个元素。
$dataset = new CsvDataset('myNewCsvFile.csv', 1);
$samples = [];
foreach ($dataset->getSamples() as $sample) {
$samples[] = $sample[0];
}
I don't understand why this isn't reading in my .csv fully, if i change the indext of sample[0] to any other index i get the following error:我不明白为什么这不能在我的 .csv 中完全读取,如果我将 sample[0] 的 indext 更改为任何其他索引,我会收到以下错误:
Notice: Undefined offset: 1 in C:\xampp\htdocs\test\index.php on line 19
This suggests to me that it's only reading the first column in each row, which is proved if i print out the array Samples i get what i would expect which is as follows:这向我表明它只读取每行中的第一列,如果我打印出数组 Samples 我得到了我所期望的结果,这证明如下:
Array
(
[0] => 1157
[1] => 1157
[2] => 1157
[3] => 1157
[4] => 1157
[5] => 1157
[6] => 1157
[7] => 1157
[8] => 1157
[9] => 1157
[10] => 1157
[11] => 1157
[12] => 1157
[13] => 1157
[14] => 1157
[15] => 1157
[16] => 1157
[17] => 1157
[18] => 1157
[19] => 1157
[20] => 1157
[21] => 1157
[22] => 1157
And so on which is correct.等等哪个是正确的。 Can anyone explain why this isn't reading in my full .csv file?谁能解释为什么这不是在我的完整 .csv 文件中读取?
As the reference document shows , you should pass the constructor a number of columns to read as a second argument and you are only asking it for one column.正如参考文档所示,您应该向构造函数传递许多列作为第二个参数读取,并且您只要求它提供一列。 In the following snippet I put another number to get more columns.在下面的代码段中,我输入了另一个数字以获得更多列。
use Phpml\Dataset\CsvDataset;
// the third argument makes it ignore the heading row
$dataset = new CsvDataset('myNewCsvFile.csv',4,true);
foreach ($dataset->getSamples() as $sample) {
print_r($sample);
}
Outputs:输出:
Array
(
[0] => 101
[1] => 201
[2] => 301
[3] => 401
)
Array
(
[0] => 102
[1] => 202
[2] => 302
[3] => 402
)
And the myNewCsvFile.csv
is;而myNewCsvFile.csv
是;
┌─────┬─────┬─────┬─────┬─────┬─────┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ 101 │ 201 │ 301 │ 401 │ 501 │ 601 │
│ 102 │ 202 │ 302 │ 402 │ 502 │ 602 │
└─────┴─────┴─────┴─────┴─────┴─────┘
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.