从JSON数组中删除元素


Delete element from JSON array

我正试图从JSON数组中删除一个元素。当用户单击删除按钮时,该操作开始。我搞不清楚出了什么问题。也许是PHP脚本上的东西。

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);
}
?>

尝试用以下内容替换foreach循环:

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