简体   繁体   中英

Delete element from JSON array

I'm trying to delete an element from a JSON array. The action starts when the user click in a delete button. I can't figure out what's wrong. Maybe it's something on the PHP script.

javascript.js

$(".delete").on('click', function(e){
        var deleteItem = e.target.id;
        console.log(deleteItem);
        $(this).closest('div').css({"text-decoration": "line-through", "color": "#e74c3c"}).fadeOut(600);
        $.ajax({
            url: 'deletejson.php',
            method: 'POST',
            dataType: 'json',
            data: { target: e.target.id},
            success: function(){
                console.log('Item was deleted');
                console.log(data);
            }
        });       

data.json

{ "prescriptions":[  
  {  
     "name":"Edogen",
     "unit":"drops",
     "dosage":"2 drops",
     "doc_name":"Dr. Wu",
     "apperance":"black",
     "days":"Monday",
     "frequency":"twice",
     "hour":"1pm"
  },
  {  
     "name":"Lexapro",
     "unit":"drops",
     "dosage":"2 drops",
     "doc_name":"Dr. Wu",
     "apperance":"black",
     "days":"Sunday",
     "frequency":"twice",
     "hour":"1pm"
  },
  {  
     "name":"Plavix",
     "unit":"drops",
     "dosage":"4 drops",
     "doc_name":"Dr. Ammy Lee",
     "apperance":"blue",
     "days":"Monday",
     "frequency":"twice",
     "hour":"10pm"
      } 
   ]}

deletejson.php

<?php

$var = $_POST["target"];
$file = "json/data.json";

$json_array = json_decode(file_get_contents($file), true);


function removeNode($var, $json_array) {
    foreach($json_array["prescriptions"] as $key => $value) { 
      if($value === $var)  
        unset($json_array["prescriptions"][$key]);           
    }

    $json = json_encode($json);      
    file_put_contents($file, $json);
}

?>

Try replacing your foreach loop with the following:

foreach($json_array["prescriptions"] as $values) { 
  foreach($values as $key => $value) { 
    if($value === $var){  
      unset($json_array["prescriptions"][$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