1

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.

neubert
  • 15,947
  • 24
  • 120
  • 212
johnfish92
  • 157
  • 2
  • 12
  • What have you tried so far? Stack Overflow isn't a code writing service... – Tom Udding Apr 28 '17 at 15:24
  • Can you put sample data of csv 1 or line here – Ajeet Kumar Apr 28 '17 at 15:24
  • @TomUdding i have edited the question with my attempts – johnfish92 Apr 28 '17 at 15:36
  • @johnfish92 the '0' (`$sample[0];`) selects the first column of your CSV file. '1' will select the second column, '2' will select the third column and so on... – Tom Udding Apr 28 '17 at 15:37
  • I added your previous code back since you just removed code and replaced it with totally different code. Maybe you should post what you're actually using. – AbraCadaver Apr 28 '17 at 15:39
  • @TomUdding I had tried that however it gave me an error message 'undefined offset' therefore i thought it was incorrect syntax with php. Do you know why it throws that error if syntacitcally its correct? Note: it throws this error on that exact line as well. – johnfish92 Apr 28 '17 at 15:40
  • @AbraCadaver i have edited the question as leaving the body of code in is getting answers which are not what i need and wasting users time. – johnfish92 Apr 28 '17 at 16:05

2 Answers2

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];
    }
}
Ajeet Kumar
  • 805
  • 1
  • 7
  • 26
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);
Barmar
  • 741,623
  • 53
  • 500
  • 612