gpt4 book ai didi

javascript - 从 JSON 数组中删除元素

转载 作者:行者123 更新时间:2023-11-30 06:52:13 24 4
gpt4 key购买 nike

我正在尝试从 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);
}
});

数据.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"
}
]}

删除json.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]);
}
}
}

关于javascript - 从 JSON 数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com