Jump to content

Nesting whiles in ifs


guyfromfl

Recommended Posts

I am writing a script that can handle either csv or xls files.  Once the data is parsed for either type it goes into an array $data  and all the same operations are done on it.

 

Right now, it is only set up to handle a csv file.

 

This is the code I have right now:

 

//Load the CSV files in the UPLOAD_PATH directory
$fileList = $fs->loadFiles(UPLOAD_PATH, "csv");

// Loop through fileList array to processes each file
foreach($fileList as $filename) {
// Attempt to open the next file in the list and process it.
if (($handle = fopen(UPLOAD_PATH.$filename, "r")) != FALSE) {

	// Create the input array
	while(($data = fgetcsv($handle, 0, ",")) != FALSE) {

               // ... do the magic

 

How do I add another set of instructions to goto the parseXLS function that performs basically what fgetcsv does?

 

I think in this case a try...catch statement would be too loose, and wouldnt be the best way.

 

What I would LIKE to do is

 

if (a csv file) {
  while(($data = fgetscv($handle, 0, ",")) != FALSE) {
} else if (an xls file) {
  while ($data = parseXLS()) {
}

// Do the magic
} // end of while

 

I know this won't work but i need to do something along those lines.  Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/224762-nesting-whiles-in-ifs/
Share on other sites

I'd put the magic in a function and do this:

 

if (a csv file) {
  while(($data = fgetscv($handle, 0, ",")) != FALSE) {
    magic($data);
  }
} else if (an xls file) {
  while ($data = parseXLS()) {
    magic($data);
  }
} else die("unknown type\n");

 

You could create a file reading class.  The class remembers if it's reading a csv file or an excel file, and has a "next line" method.  You keep calling the next line method until there's no more lines left.  So instead of abstracting out the line processing magic, you've abstracted out the file reading magic.

 

Edit: change "file processing" to "line processing"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.