0

I wondered if it was possible to read a csv file written like this in symfony using League csv or something else.

      water_level,2,456,345
      wind_speed,25,456,56
      food_level,10.4,123,23
      animal_count,56,34,124
      number_of_machines,150,345,54
      machineId,1234567,1234568,1234567

Header in the first column and data in the next columns.

Right now, I can read the files when the header is in the first row, I just want to know if it's possible to read it the other way!

I tried transposing but I get an error. I don't really know what's causing it if the array really is transposed.

    $pathString = implode($newFilesPath);
    $reader = (Reader::createFromPath($pathString))->setHeaderOffset(0);
    $results = $this->transpose(iterator_to_array($reader->getRecords()));

    foreach ($results as $row) {

        $properties = (new AppProperty)
            ->setWaterLevel($row['water_level'])
            ->setWindSpeed($row['wind_speed'])
            ->setFoodLevel($row['food_level'])
            ->setAnimalCount($row['animal_count'])
            ->setNumberOfMachines($row['number_of_machines'])
            ->setMachineId($row['machineId'])
            ->setDate(new \DateTime());

            $this->em->persist($properties);
    }

    $this->em->flush();
 }

private function transpose ($array){
    return array_map(null, $array);
}

The error:

Argument 1 passed to App\Entity\Property::setWaterLevel() must be of the type int or null, string given.
It looks like the transpose just didn't work.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Michaeldc
  • 45
  • 10
  • You can transpose the array. Here some solutions https://stackoverflow.com/questions/797251/transposing-multidimensional-arrays-in-php – Matteo Jun 05 '19 at 19:35
  • Would it affect a lot the efficiency of the program to transpose a 1000rows/2colums csv file? – Michaeldc Jun 05 '19 at 20:27
  • what is the expected output of this example you are try to do ? – Yassine CHABLI Jun 05 '19 at 21:44
  • The example I wrote in my question is irrelevant, in my program, I'm trying to read a csv file with 1000 rows and 2 columns. So it's a 1000 rows of properties. If the only way is to transpose it to obtain a 1000 column of properties, then that would be the expected output. (2 rows/1000 columns) – Michaeldc Jun 06 '19 at 12:15
  • I tried transposing but I end up getting this error; _Argument 1 passed to App\Entity\Property::setWaterLevel() must be of the type int or null, string given_. I'll edit my question a little bit. – Michaeldc Jun 06 '19 at 13:58
  • Did you try converting the value to integer? something like: ->setWaterLevel((int) $row['water_level']) – Stiff Roy Nov 14 '19 at 10:49

0 Answers0