1

I have file that is delimetered by a comma like below

Big2,red,0,Y
Big2,blue,0,N
Big2,green,1,N
Big6,red,0,Y
Big6,blue,0,N
Big6,green,1,N
Big6,yellow,0,Y
Big6,black,0,Y

Following is the code I used to read the file

$file_content = explode("\n",(file_get_contents("inven.csv"))); 
foreach ($file_content as $key => $value)  {    
    $value = str_replace(array('\'', '"'), '', $value);  
    $line_records = explode(',', $value);   
    $reference = trim($line_records[0]);
    $option = trim($line_records[1]);
    $quantity = trim($line_records[2]);
    $discontinued = trim($line_records[3]);
}

I want to check for the following condition and perform some action

  1. If the 1st, 2nd and 4th field are the same for all lines
  2. If all "Big2" rows have the 3rd field = 0 and the 4th field = Y
Ebenezer Isaac
  • 772
  • 1
  • 8
  • 31
Mike Gl
  • 13
  • 2
  • 1
    Show code an what you've tried. – AbraCadaver Jun 04 '20 at 16:29
  • 1
    is this what you are looking for? [https://stackoverflow.com/questions/13246597/how-to-read-a-large-file-line-by-line] – Floyd Lawton Jun 04 '20 at 16:31
  • Welcome to SO! Please read over [how to ask](https://stackoverflow.com/help/how-to-ask) and update your question with a [minimal, complete example](https://stackoverflow.com/help/minimal-reproducible-example). Can you provide an example of what sort of result you're expecting with the sample data set you provided? Also please provide your current PHP code so we can see what you have so far. – WOUNDEDStevenJones Jun 04 '20 at 16:33
  • @FloydLawton I updated me query so I hope it is more clear thank you for the reply – Mike Gl Jun 05 '20 at 12:08

1 Answers1

0

Hope this solves your problem

$references = $options =$quantities = $status = array();
$file_content = explode("\n",(file_get_contents("inven.csv"))); 
foreach ($file_content as $key => $value)  {    
    $value = str_replace(array('\'', '"'), '', $value);
    $line_records = explode(',', $value);
    $references[] = trim($line_records[0]);
    echo end($references);
    $options[] = trim($line_records[1]);
    echo end($options);
    $quantities[] = trim($line_records[2]);
    echo end($quantities);
    $status[] = trim($line_records[3]);
    echo end($status);
}
$flag = true;
foreach(array_combine($references, $quantities, $status) as $ref => $quantity => $stat) {  // foreach line throws and error
    if($ref == 'Big2') {
        if($quantity != 0 || $stat != 'Y'){
            $flag = false;
            break;
        }
    }
}

if (count(array_unique($references)) === 1 && count(array_unique($options))==1 && count(array_unique($status))==1) {
    //Do action if the 1st, 2nd and 4th field are the same for all lines
}

if ($flag) {
    //Do action if all "Big2" rows have the 3rd field = 0 and the 4th field = Y
}
Mike Gl
  • 13
  • 2
Ebenezer Isaac
  • 772
  • 1
  • 8
  • 31