您好我正在寻找如何根据ID值删除json文件中的数组。
这是我的json文件
[
{
date: "3/7/2017",
title: "kjjnkjnjn",
category: "Automobile",
ville: "Labas",
decription: "nlknlknklnkjlnkl",
mail: "mathieufrobert@yahoo.fr",
telephone: "0777878988",
pseudo: "kknklnkln",
prix: "10",
mdp: "0000",
id: "5959785fde3bc26610"
},
{
date: "3/7/2017",
title: "kjjnkjnjn",
category: "Automobile",
ville: "Labas",
decription: "nlknlknklnkjlnkl",
mail: "mathieufrobert@yahoo.fr",
telephone: "0777878988",
pseudo: "kknklnkln",
prix: "10",
mdp: "0000",
id: "6848675fde3bc26610"
},{
date: "3/7/2017",
title: "kjjnkjnjn",
category: "Automobile",
ville: "Labas",
decription: "nlknlknklnkjlnkl",
mail: "mathieufrobert@yahoo.fr",
telephone: "0777878988",
pseudo: "kknklnkln",
prix: "10",
mdp: "0000",
id: "5737554fde3bc26610"
}
]
这是我的php文件(它是来自另一个php的副本)
<?php
$file = $_POST["id"];
$animals = file_get_contents('text.json');
$animals = json_decode($animals, true);
foreach ($animals as $key => $value) {
if (in_array($file, $value)) {
unset($animals[$key]);
}
}
$animals = json_encode($animals);
?>
我的Ajax代码
$("#5959785fde3bc26610").click(function() {
$.ajax({
url: "delete.php",
type: "POST",
data: {
id: "5959785fde3bc26610",
},
success: function (result) {
Materialize.toast('Annonce Supprimé!', 4000);
}
});
});
这就是我希望我的json文件看起来像
的方式[
{
date: "3/7/2017",
title: "kjjnkjnjn",
category: "Automobile",
ville: "Labas",
decription: "nlknlknklnkjlnkl",
mail: "mathieufrobert@yahoo.fr",
telephone: "0777878988",
pseudo: "kknklnkln",
prix: "10",
mdp: "0000",
id: "6848675fde3bc26610"
},{
date: "3/7/2017",
title: "kjjnkjnjn",
category: "Automobile",
ville: "Labas",
decription: "nlknlknklnkjlnkl",
mail: "mathieufrobert@yahoo.fr",
telephone: "0777878988",
pseudo: "kknklnkln",
prix: "10",
mdp: "0000",
id: "5737554fde3bc26610"
}
]
提前感谢您的帮助。
答案 0 :(得分:2)
首先,您将在PHP中阅读JSON,如下所示:
<?php
$id = $_POST['id'];
// stop if it's non-numeric
if (!preg_match('/^\d+$/', $id)) {
die('Don’t hack us.');
}
$file = 'the.json';
$data = file_get_contents($file);
$list = json_decode($data);
// now, we will search the ID
for ($i = 0; $i < count($list); $i++) {
// if we found it,
if ($list[$i]->id === $id) {
// we remove it
unset($list[$i]);
break;
}
}
// make the numeric array consecutive again
$list = array_values($list);
// write the resulting JSON to disk
$fp = fopen($file, 'w');
fwrite($fp, json_encode($list));
fclose($fp);
答案 1 :(得分:-2)
我建议你使用ES6 Array.prototype.filter。
const deletePropWithId = (array, id) => {
return array.filter((obj) => obj.id[id] !== undefined);
}