0

I am trying to sort through a JSON array and remove an item that the user tells the page to delete. I have used some echos to see if the values match, and even when the values of $value['AD'] and $lineToRemove are the same my If statement is not catching it and it skips to the Else section. I have tried without my values being string, I have tried with ===, and I have tried a few different solutions.

Here is the code I have at the moment.

$str = file_get_contents($file2);
$json = json_decode($str, true); // decode the JSON into an associative array

$match = "We have a match!";
$test = "Sorry, no match found.";

foreach ($json as $field => &$value) {
if ((string)$value['AD'] == (string)$lineToRemove) {

    echo '<pre>' . print_r($match, true) . '</pre>';

    unset($json[$field]);
    $json = array_values($json);
    var_dump($json);
}
else {
    echo '<pre>' . print_r($test, true) . '</pre>';
}
}

$finalArray = json_encode($json);
file_put_contents($file2, $finalArray);

The $lineToRemove is a variable of the file name the user is trying to delete. Here is a sample of my JSON:

[
    {
     "AD":"image-1.png",
     "DURATION":1000
    }
]

I have tried the answer to this question but it didn't work, the code I currently have is the closest I have come to this working.

Community
  • 1
  • 1
Bryan
  • 35
  • 4

1 Answers1

0

I figured it out. The variable $lineToRemove had a line break at the end of it, thus making it different. Here is the working code if anybody is interested.

    // Get contents of JSON array to remove items from the JSON array
    $str = file_get_contents($file2);
    $json = json_decode($str, true); // decode the JSON into an associative array

    // Loop through all of the items in the JSON array to find the file you want to delete
    foreach ($json as $field => &$value) {

        // Remove the line break at the end of the $lineToRemove variable so you
        // can compare it to the $value['AD'] variable
        $lineToRemove = str_replace("\n", '', $lineToRemove);;

        if ($value['AD'] == $lineToRemove) {
            // Remove $lineToRemove from JSON array
            unset($json[$field]);
            $json = array_values($json);
        }
    }

    // Save new array to JSON file
    $finalArray = json_encode($json);
    file_put_contents($file2, $finalArray);
Bryan
  • 35
  • 4