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. 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. I am new to PHP and don't understand why this would happen.
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.
$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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.