N
N
Nikita Nikonov2020-04-14 10:55:45
PHP
Nikita Nikonov, 2020-04-14 10:55:45

How to remove row with duplicate value from CSV (PHP)?

There is an array in php array

$list = array (
              array('', $_POST['subject'], $_POST['time'], $_POST['text'], $_POST['name_html'],''),
          );

And there is a CSV file.
First, I add this array to the end of the file in array and I get one new line with the data received from the POST request.
$list = array (
              array('', $_POST['subject'], $_POST['time'], $_POST['text'], $_POST['name_html'],''),
          );

          $fp = fopen('db/cards.csv', 'a');

          foreach ($list as $fields) {
              fputcsv($fp, $fields);
          }

          fclose($fp);


After that, I need to go through the same file and remove from it the first (if you go from top to bottom) line that appears, where the same $_POST['subject'] will be mentioned. Accordingly, I just want to remove the old $_POST['subject'] value from the database. And I don't know how to do it.

All code

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2020-04-14
@RickCastle2018

i just want to remove old $_POST['subject'] value from db

Dear Nikita from 7"B", I don't want to seem rude, but for this task it's better to use a real database (at least PDO + SQLite), and not emulate a database on csv files.
And if on the merits of the question, then something like this is done
<?php
$list = [];
if(($handle = fopen("db/cards.csv", "r")) !== false)
{
    while(($data = fgetcsv($handle, 1000, ",")) !== false)
    {
        $subject = $data[1];
        $list[$subject] = $data; //<--- ключевой момент
    }
    fclose($handle);
}

//теперь в $list только строки с уникальным $subject
print_r($list);

//перезаписываем csv данными из $list
//тут ваш код

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question