简体   繁体   中英

Delete rows from a file based on an array I got from a sql query

Hi guys I have a text file that contains several lines, let's say:

line1
line2
line3
line4
line5

based on a query to a mysql database I get some values, for example

line1
line3

I want to take the array from the query and delete those values from the text file so that the result is:

line2
line4
line5

I don't have problems to get the values from the db, my problem is how to delete the lines from the text file?

Something like this if there is only one instance of the value in the file:

$rows = your_fetch_all_func();  //or while($rows[] = your_fetch_assoc_func()) {}
$lines = file('path/to/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($rows as $row) {
    if($key = array_search($row['column'], $lines)) {
        unset($lines[$key]);
    }
}

If the data from the database can be in the file more than once, then use something like this, though there is probably a slicker way:

foreach($rows as $row) {
    if($keys = array_keys($lines, $row['column'])) {
        foreach($keys as $key) {        
            unset($lines[$key]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM