从JSON数组中删除元素

时间:2016-03-26 04:42:59

标签: javascript php jquery arrays json

我试图从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);
}

?>

1 个答案:

答案 0 :(得分:0)

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

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