Javascript 使用从前端发送的索引从数组中删除项

Javascript 使用从前端发送的索引从数组中删除项,javascript,php,json,Javascript,Php,Json,我正在尝试从php数组中删除一个项 我有一个用于存储数据的json文件。json文件如下所示 { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ "a.jpg", "b.jpg", "c.jpg" ] }, "1.4952754451E+12": {

我正在尝试从php数组中删除一个项

我有一个用于存储数据的json文件。json文件如下所示

{
    "1.49514754373E+12": {
        "description": "I don't like it",
        "fileNames": [
            "a.jpg",
            "b.jpg",
            "c.jpg"
        ]
    },
    "1.4952754451E+12": {
        "description": "hey there",
        "fileNames": [
            "a.jpg"
        ]
    }
}
我的php代码如下所示

if ($_SERVER['REQUEST_METHOD'] === 'POST')  {

  //the id is sent from the front end. In this case it is '0';
  $data =  $_REQUEST['id'];

  $index = json_decode($data);

  // get json from file
  $json = file_get_contents('test.json');

  // turn json into array
  $masterArr = json_decode($json, true);

  unset($masterArr[$index]);

  // turn array back to json
  $json = json_encode($masterArr, JSON_PRETTY_PRINT);

  // save json to file
  file_put_contents('test.json', $json);

  echo $json;

?>
我尝试使用
unset
-
unset($masterArr[$index])但这不起作用。有人能看出我做错了什么吗

当我
echo$index
时,我得到
0

var\u dump(masterArr)
给了我

array(2) {
  ["1.49514754373E+12"]=>
  array(2) {
    ["description"]=>
    string(15) "I don't like it"
    ["fileNames"]=>
    array(3) {
      [0]=>
      string(5) "a.jpg"
      [1]=>
      string(5) "b.jpg"
      [2]=>
      string(5) "c.jpg"
    }
  }
  ["1.4952754451E+12"]=>
  array(2) {
    ["description"]=>
    string(17) "hey there"
    ["fileNames"]=>
    array(1) {
      [0]=>
      string(5) "a.jpg"
    }
  }
}
在上面的例子中,我试图删除

"1.49514754373E+12": {
    "description": "I don't like it",
    "fileNames": [
        "a.jpg",
        "b.jpg",
        "c.jpg"
    ]
}

unset()销毁指定的变量。如果要删除文件,请使用php的unlink函数取消设置任何变量,使用delete语句:

delete favorites.favorites[1].items[1]
如果要从数组中实际删除某个项,以便数组中该项之后的所有项向下移动到较低的索引,可以使用以下方法:

favorites.favorites[1].items.splice(1, 1);

对于
.splice()
,您将传递要开始修改数组的索引,然后传递要删除此
的项数。splice(1,1)
将从索引1删除1项。

根据我看到的注释,如果
$index
0
,您将删除所有内容

因此,只需按以下步骤操作即可

$data =  $_REQUEST['id'];

$index = json_decode($data);
if($index == 0){
  file_put_contents('test.json', "");
  // you can also return your proper response here.
  return;
 }

输出
$masterArr
$index
的值,并查看数组中是否有此键。在将$json保存到文件之前,请在此处显示其内容show$masterArr和$index请模块化您的代码。我推荐一个类,它只处理获取和保存文件中的数据。也是一个函数,它向删除它的数据传递一个索引。另一个输出完整数据集的函数。在另一个类中,您可能希望验证接收到的数据。我建议phpunit对所有这些特性进行单元测试#ftw@KrisRoofe知道了!这需要是动态的。如果object中有多个项,该句柄仅适用于
0