[英]Using samples() with 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('myCsvFile.csv', 1);
$samples = [];
foreach ($dataset->getSamples() as $sample) {
$samples[] = $sample[0];
}
However this gives me the first element of each array, if i change the $sample[0] to $sample[4]
as i thought syntactically this would work i get an Undefined offset on the line in question.然而,这给了我每个数组的第一个元素,如果我将$sample[0] to $sample[4]
更改$sample[0] to $sample[4]
因为我认为这在语法上会起作用,我会在相关行上得到一个未定义的偏移量。 I am new to PHP and don't understand why this would happen.我是 PHP 新手,不明白为什么会发生这种情况。
If the code is left as above and printed out it looks like the following:如果代码保留如上并打印出来,则如下所示:
Array
(
[0] => 1157
[1] => 1157
[2] => 1157
[3] => 1157
[4] => 1157
[5] => 1157
[6] => 1157
[7] => 1157
[8] => 1157
...and so on. ...等等。
You can try this你可以试试这个
$csv = array();
$csvNewArray = array();
$lines = file('myCsvFile.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value);
if(isset($csv[$key][4])){
$csvNewArray[$key] = $csv[$key][4];
}
}
Use fgetcsv()
to read from the file, then access the appropriate element of these arrays to get the fifth item of each row.使用fgetcsv()
从文件中读取,然后访问这些数组的相应元素以获取每行的第五项。
$fh = fopen("myCsvFile.csv", "r") or die("Can't open CSV file\n");
$csv = array();
$sample = array();
while ($row = fgetcsv($fh)) {
$csv[] = $row;
$sample[] = $row[4];
}
fclose($fh);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.