Home>
$json = file_get_contents ("php: // input");
$json_data = json_decode ($json, true);
$ID = $json_data ['id'];
$filearr = file ('send.txt');
foreach ($filearr as $no =>$val) {
 }
id = 1, Product = Pen
id = 2, Product = Chair
id = 3, Product = Eraser

I want to compare the received id with the id stored in the txt file and delete the data with the same id, but store the txt file in an associative array. I want to compare the sent id with the loop, delete it, and store it again in a txt file, but I can only understand the above. What should I do?

php
  • Answer # 1

      

    Delete data with the same id

    Change the way of thinking and think that "data with the same id is not output to a file".

    /* read from file * /
    $filearr = // sample, so we read
               ["id = 1, product = pen",
                "id = 2, product = chair",
                "id = 3, product = eraser"];
    / * Id to delete * /
    $ID = 2;// Since it is a sample, it is set to 2 as a direct value
    / * Array for output * /
    $newLines = array ();
    foreach ($filearr as $no =>$val) {
        / * Get the file id (value after = in the first column) * /
        $cols = explode (",", $val);// Divide by "," and put into array
        $keyval = explode ("=", $cols [0]);// Divide the first column by "=" and put it in the array
        if ($keyval [1] == $ID) {// If the file id and $ID are the same
            / * Move to next line * /
            continue;
        } else {// If the file id and $ID are different
            / * Append to output array * /
            $newLines [] = $val;
        }
    }
    / * Write $newLines to file send.txt * /
    var_dump ($newLines);// Display as var_dump because it is a sample

    Execution result

    array (2) {
      [0] =>
      string (18) "id = 1, product = pen"
      [1] =>
      string (24) "id = 3, Product = Eraser"
    }