0

I have a CSV file with content similar to the following:

"Red",Red Coat
"",Red Dog
"",Red Car
"Blue",Blue Stuff
"Green",Green Stuff
"",Green Grass

I can read this and am output via PHP.

if (($handle = fopen("file.csv", "r")) !== FALSE) {
$row=0;
$csv_row = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$csv_row = $data;

      $previous=$csv_row[0]
      $colour=$csv_row[0]
      if $colouris null then $colour=$previous;
      echo $colour." ".$csv_row[1]."<BR>";

}
fclose($handle);
}

And this will show me the Output with blanks for missing items.

Im not a Developer so forgive the question and ugly logic below. I want to use the existing value of $colour for the next $colour if its blank.

So something like:

      $previous=$csv_row[0]
      $colour=$csv_row[0]
      if $colour is null then $colour=$previous;

So for my CSV would show me:

 Red Red Coat
 Red Red Dog ( previously Colour was empty)
 Red Red Car ( previously Colour was empty)
 Blue Blue Stuff
 Green Green Stuff
 Green Green Grass ( previously Colour was empty)

Any help appreciated!

1
  • I'm not sure but I don't think it's null, I think it's value is empty, try if $colour == "" Commented Feb 5, 2014 at 15:40

2 Answers 2

1

Change this :

if $colour is null then $colour=$previous;

To this :

if (!$colour)
{
    $colour = $previous;
}

So if $colour is null, or empty, $colour will take the value from $previous.

Also, I think you may want to change this :

$previous=$csv_row[0];
$colour=$csv_row[0];

To this :

$previous=$csv_row[0];
$colour=$csv_row[1];
Sign up to request clarification or add additional context in comments.

Comments

1

You just need to change a small amount in your code. The $previous variable is not necessary.

This works -

if (($handle = fopen("a.php", "r")) !== FALSE) {
$row=0;
$csv_row = array();

$color = "";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $csv_row = $data;
    //Don't update $color if no color available.
    if($csv_row[0] != null){
        $color = $csv_row[0];
    }
    echo $color." ".$csv_row[1]."<BR>";
}
fclose($handle);
}

/*
OUTPUT:
Red Red Coat
Red Red Dog
Red Red Car
Blue Blue Stuff
Green Green Stuff
Green Green Grass
*/

1 Comment

Thank you both , I ended up using this as it was a direct copy paste for me. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.