Avatar of Jazzy 1012
Jazzy 1012
 asked on

Must run twice for it to work fully

$find = '.5010.';
$directory_with_files = './'.date('m-d-Y');
$dh  = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
    if(in_array($filename, array('.', '..')) || is_dir($filename))
        continue;

    $files[] = $filename;
}

foreach($files as $file)
{
    //find only 5010 files
    if(stripos($file, $find) !== false)
    {
        // open the 5010 file
        $handle = fopen(date('m-d-Y').'/'.$file, "r");
        $file_content = file_get_contents(date('m-d-Y').'/'.$file);
        $handle2 = fopen(date('m-d-Y').'/'.$file, "r");
        $file_content2 = file_get_contents(date('m-d-Y').'/'.$file);
    
        if ($handle) {
            $header = '';
            $name = '';
            $footer = '';
            $payor_blocks = array();
            
            
            // determine if file has more than one payor
            $payor_count = substr_count($file_content, 'N1');
            //if the file has more than one payor
            if($payor_count > 1) {
                //read the file line by line
                $header_end = false;
                $block_start = false;
                $count = 1;

                
           if($handle2){
                $line_number = 0;
                $line_stop= array();
                while (($line1 = fgets($handle2)) !== false) {
                
                	$line_number++;
                
                	if(strpos($line1, 'CAT') !==false){
                		 
                		$line_stop[] = $line_number;
                	}
                
                }
                $footer_line = count($line_stop)-2;
                $footer_line = $line_stop[$footer_line];
                
                
                $line_number = 0; }
                
                //look for occurances of CAT and what line each on is on
               
                while (($line = fgets($handle)) !== false) {
                    $line_number++;
                   

                    //look for the first payor block
                    if(strpos($line, 'N1') !== false || $block_start) {
                        $header_end = true; $block_start = true;
                         if(strpos($line, 'N1') !== false) {
                         	$count++;
                         }  
                            
                        //see if the block finished
                         if($line_number == $footer_line) {
                         	$block_start = false;
                         	$payor_blocks[$count] .= $line;
                         	$count++;
                         }
                  $payor_blocks[$count] .= $line;
                    } else {
                        //append to the header
                        if($header_end) {
                            $footer .= $line."\n";
                           
                        } else {
                            $header .= $line."\n";
                        }
                    }
                }
               
                //get payor blocks and create a file foreach payor
                $new_files = array();
                foreach($payor_blocks as $block) {
                    $filename = date('m-d-Y').'/'.$file . "_" . $count;
                    $count++;
                    $new_files[] = array(
                        'name' => $filename,
                        'content' => $header."\n".$block."\n".$footer	
                    	
                    );
                 
                }
                //loop through new files and create them
                foreach($new_files as $new_file) {
                    //create file
                	$myfile = fopen($new_file['name'], "w");
   
                    //put contents in the file               	
                	fwrite($myfile, $new_file['content']);	
              		//close the file
                	fclose($myfile);
                }
                
             echo "<pre>" . print_r($new_files, true) . "</pre>";
            } 
            else{

            	// DO what u were doing in script #1
           while (($line = fgets($handle)) !== false)
            {
            	$refid = 'REF';
            	
            	if(stripos($line, $refid) !== false)
            	{
            		$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
            		$refnumber = trim($refnumber);
            	
            		if($refnumber != '')
            		{
            			$refnumber = '_'.$refnumber.'_';
            			$filerenamed = str_replace($find, $refnumber,$file);
            			copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
            		}
            		echo $refnumber . "\n";
            		
            	}
            
            	}
            }
        }

    }
    		// DONE - close the file
    			fclose($handle);
}

foreach($files as $fiftyfile){
	if(stripos($fiftyfile, $find) !== false){

		$handle3 = fopen(date('m-d-Y').'/'.$fiftyfile, "r");
		$file_content3 = file_get_contents(date('m-d-Y').'/'.$fiftyfile);

		if ($handle3) {

			if(unlink('./'.date('m-d-Y').'/'.$fiftyfile))
			{
				echo "file named $fiftyfile has been deleted successfully";
			}
			else
			{
				echo "file is not deleted";
		}
}
}

}
		//combine all files
		file_put_contents("combined.txt", ""); // Empty the file first
		foreach ($files as $my_file) {
		$handle4 = fopen(date('m-d-Y').'/'.$my_file, "r");
		$file_content4 = file_get_contents(date('m-d-Y').'/'.$my_file);
		file_put_contents("combined.txt", $file_content4, FILE_APPEND);

}

Open in new window


The code above works fine, however I need to referesh my browser twice for it to run. The first time it just splits then the second time it renames, I was wondering why this issue occurs?
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
Ray Paseur

Sigh.  This script contains 15 if statements and 4 else statements in 174 lines of code.  We don't write programs like this any more, because we have come to learn that M>10 cyclomatic complexity makes understanding and debugging "spaghetti code" very, very hard.  You're likely to get much better results if you bring some kind of object-oriented structure to the code.

Why OO programming?  Because objects can be mocked, and can therefore be formally tested against assertions.  A good set of test data seems to be the important thing that is missing from many of your questions.  I urge you to write a PHP script that will create all of the necessary directories and test data files, and post that script here.  Please see: SSCCE.  Then we can copy the script, install the script, run it.  This will let us see and use the test data.  Without this, we're just guessing about what might be going wrong in such a convoluted block of logic.  We might guess right, but we are not likely to be able to simulate your test data, or take on your debugging task, unless you move this request to E-E Gigs (which could be a very good idea).

When you're new to programming, the necessary step of creating test data seems like "make-work" but once you being to understand the processes we use for software development, you will come to the same conclusion that all experienced programmers reach:  The test data serves two purposes.  Obviously, it lets us test our programs.  Less obviously but more important, it forces us to consolidate our thinking, and thinking before committing our ideas to code is a really good idea!
Jazzy 1012

ASKER
ISA*00*          *00*          *ZZ*2274      *ZZ*362931550      *16091236*^*00501*00079*0*P*:~
GS*HP133052274*36290160902*1236*1*X*0010X221A1~
ST*835*0001~
BPR*H*0*C*NON********20160901~
TR1*C16245N54171570*13236610*CP2016541715700~
REF*EV*IL85010~
DTM*405*160901~
N1BLUE ILLINOIS~
N3*300 E RANDOLPH~
N4*CHICAG99~
REFSB621~
PER*BL~
N1*PESR M D*XX*1467520924~
N3*280AVE~
N4*CHA06915~
REF*TJ*332366562~
LX*1~
CLP*79270C18*1*2510*140.34*12*0201622650825U60X00*11*1~
NM1*74*1**O****C*IBT878327840~
REF*1L*0033390000~
REF*CE*PED PROGANIZATIO~
DTM*232*20160805~
DTM*233*200805~
DTM*050*20160813~
AMT*AU*140.34~
SVC*HC:99213:25*150*0**1~
DTM*472*0160805~
CAT*PR*1*78.62~
CAT*CO*45*.38~
REF*6R*79270C18L1~
AMT*B68.62~
SVC*HC:96372*60*0**2~
DTM*4720160805~
CAT*PR*1*60~
REF*6R*79270C18L2~
AMT*B6*60~
SVC*HC:J3301*11*0**1~
DTM*472*20160805~
CAT*PR*1*1.72~
CAT*C*45*9.28~
REF*6R*790C18L3~
AMT*B6*1.72~
SVC*HC:J0171*30*0**1~
DTM*472*20160805~
CAT*CO*1*30~
REF*6R*79270C18L4~
LQ*HE*M119~
LX*2~
CLP*79007C2K*1*150*0**12*0201623550T23060X00*11*1~
NM1*QC22377630~
REF*1L*0000FEP000102~
REF*CENIZATIO~
DTM*232*20160808~
DTM*233*20160808~
DTM*050*20160820~
AMT*F5*0~
SVC*HC:99213*150*0**1~
DTM*472*20160808~
CAT*CO*16*150~
REF*6R*79007C2KL1~
LQ*HE*N4~
SE*61*0001~
ST*835*0002~
BPR*H*0*C*NON************20160901~
TRN*1*C16245N54170180*1361236610*CP20160901N541701800~
REF*EV*IL8355010~
DTM*405*20160901~
N1 INSURACE COMPANY*XV*87726~
N3*99ROAD~
N4*39664~
REF87726~
PER*CXRVICES INC*TE*8778423210~
PER*BL**UR*WWW.TEDHEALTHCAREONLINE.COM B2C~
N1*PE*OD ANKLE CLINIC SC*XX*1245208453~
N3*270 E CENTER DR 120~
N4*VERN734~
LX*1~
CLP*65158.11011*1*150*135.45**16*OEB8141356100*31*1~
NM1*QC*1*OHARA*ANNA****MI*954370786~
NM1*74*ANNE*M~
NM1*82*DPM*J***XX*1669441689~
REF*1L*12809~
REF*CE*ILLINOIS DEPARTMENT OF CMS~
DTM*050160822~
DTM*232*20160810~
AMT*AU*138.21~
SVC*HC305*150*135.45**1~
DTM*72*20160810~
CAT*CO*45*11.79**253*2.76~
AMT*B6*1.21~
LX*2~
CLP*63175.11011*1*150*135.45**16*STM7070402700*31*1~
NM1*QC*1*TAR***MI*854953882~
NM1*82*1*MM*J***XX*1669441689~
REF*1L*18000~
REF*CIC PLAN 1~
DTM*050*20160808~
DTM*232*2016622~
AMT*AU*138.21~
SVC*HC:9905*150*135.45**1~
DTM*472*160622~
CAT*CO*45*11.79**253*2.76~
AMT*B6*138.21~
SE*42*0004~
ST*835005~
BPR*I*124384877*DA*1470858534*141187726*01*081904808*DA*5201617759*20160906~
TRN*1*1226214561*1411245*000087726~
DTM*400160830~
CAT*CO*9*90~
REF*6RE1916737576411-02~
LQ*HE*N0~
SE*410008~
GE8*1~
IEA*0005579~

Open in new window


This is my beginning file, then it splits and becomes 2 (blue, & insurance) then i need to run it again to put the REF
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jazzy 1012

ASKER
Do you need me to give you more than one file And the name of the file i posted it "347568.5010.3586.ed3"
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Ray Paseur

OK, so help me get this straight.  If I take the test data and put it into my /storage/ directory, named /storage/347568.5010.3586.ed3, then I should be able to run the script from inside the storage directory to see what it does?  Does that sound right to you?
Jazzy 1012

ASKER
Yes  but make sure to change the directory path in the code, because mine is todays date
Ray Paseur

Thanks, I'll look out for that, and will take a deeper look at it this afternoon.  As long as I keep everything isolated in my /storage/ directory, there should be no issues
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Jazzy 1012

ASKER
Okay thanks, much appreciated!
Jazzy 1012

ASKER
Thanks! I solved it.
Ray Paseur

Congrats! :-)
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy