0

I'm importing data from a CSV via PHP.

On some lines of the CSV, column 1 has a value, and on other lines it does not have a value. Column 2 always has a value.

If column 1 is empty and column 2 has a value, I would like column 1 to use the previous value in column 1. For example

|-------|-------|
| Col 1 | Col 2 |
|-------|-------|
|   A   |   2   |
|   B   |   5   |
|   C   |   3   |
|       |   1   |
|   D   |   7   |

Would return

 A2 
 B5
 C3
 C1
 D7

I can use prev() on an array, but as $data[0] is a string I can't use prev()

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($i > 0) {  
            if ($data[0]=='' && $data[1]!=='') { 
            echo prev($data[0]).$data[1]'<br/>';
            } else { 
            echo $data[0].$data[1]'<br/>';
            }
        }
    $i++;
}

Banging my head against a wall for hours now, so I'd love a pointer!

1
  • Simply stash the value of column one and use it if you find it blank on a line. Commented May 1, 2018 at 12:31

3 Answers 3

1

This should work as long as the first row is not empty...

$x = null;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($i > 0) {
            $x = $data[0] == '' ? $x : $data[0];
            // this is like: if $data[0] is empty then use $x else say $x is $data[0].
            // Like that you can keep track of the previous value.
            // If there is one overwrite with the new one else keep the old value
            echo $x.$data[1]'<br/>';
        }
    $i++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Caramba. I tried that before but had been storing the variable inside the while loop!
@charliechina no worries, that happens to all of us once. happy coding
1

You can store previous value in the variable and use that

$previousColumn1 = '';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($i > 0) {  
            if ($data[0]=='' && $data[1]!=='') { 
            echo $previousColumn1.$data[1]'<br/>';
            } else { 
            $previousColumn1 = $data[0];
            echo $data[0].$data[1]'<br/>';
            }
        }
    $i++;
}

Comments

0

As has been mentioned, just storing the previous value and overwriting it any time a new value is given will do the job. It will assume that if the first row is blank that the $prev value you provide outside the loop will be used...

$prev = '';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $prev = $data[0]?:$prev;
    echo $prev.$data[1].PHP_EOL;
}

This uses the short form of ?: to say if there is a value for $data[0] - then use it, otherwise use $prev.

Comments

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.