0

I followed the solution introduced here https://stackoverflow.com/a/36041188/11295637 to create a new csv file and fetch specific columns of a large csv file to the new one. But, I get this error: Uncaught Error: Call to a member function insertOne() on null.

The code is as follows:

php

$new= Writer::createFromPath('path\to\file', 'w+');
$filename= Reader::createFromPath($filename, 'r');
          $filename->setOffset(1);
          $filename->each(function ($row) use ($indexes) {
            $new->insertOne($row);
            return true;
          });

The problem is that the new variable is undefined. I tried also

php
$new= Writer::createFromFileObject(new SplTempFileObject());

But I got the same error.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Jazal
  • 21
  • 1
  • 5

1 Answers1

0

In PHP, if you want to reference a variable defined outside of a function, you must either (a) use a use qualifier in your anonymous function signature or (b) use a global statement inside your function.

In your case, you have a use qualifier but it references a variable $indexes. I don't see an $indexes variable in your code, so you either need to add $new to that list or replace $indexes with $new.

$new = Writer::createFromPath('path\to\file', 'w+');
$filename = Reader::createFromPath($filename, 'r');
$filename->setOffset(1);
$filename->each(function ($row) use ($new) {
    $new->insertOne($row);
    return true;
});

To select only the indexes specified in the $indexes variable, you should select certain keys from $row and then rebuild a new row. You can use array_flip and array_intersect_key to do that.

// convert [cat, dog] => [cat => 0, dog => 1]
$indexKeys = array_flip($indexes);
$filename->each(function ($row) use ($new, $indexKeys) {
    $selectedCols = array_intersect_key($row, $indexKeys);
    $new->insertOne($selectedCols);
    return true;
});
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68
  • 1
    Yes, that solved the issue. The $indexes variable is already defined, it is just omitted from the above code snippet. I added the $new and that solves the problem. Thank you :) – Jazal Apr 01 '19 at 22:34
  • The $indexes variable represents the indexes of the columns to fetch from the large csv file. When I added $new to the list of use together with $indexes, all the columns from the $filename are fetched! any hints on how to extract only the data specified in the indexes – Jazal Apr 01 '19 at 23:01
  • Normally that would be a second question, but since the $indexes variable was already present, I've added a second example showing how to select only the requested indexes. – Chris Middleton Apr 01 '19 at 23:15