Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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. 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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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];
    }
}
over 4 years ago · Santiago Trujillo Report

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!