我可以用PHP成功地删除JSON数组中的元素,但是我不明白为什么JSON数组在删除最后一个元素后会改变语法。
下面是我的User.json文件:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
},
{
"id": "hgF5D4es"
}
]下面是我的delete.php脚本:
$className = "Users";
// get the index
$index = (int)$_GET['index'];
//fetch data from json
$data = file_get_contents($className. '.json');
$data_array = json_decode($data, true);
// delete the row with the index
unset($data_array[$index]);
//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents($className. '.json', $data);所以,如果我转到下面的URL,只是为了测试我的php函数:
https://example.com/delete.php?index=0该脚本成功删除了JSON数组的第一个元素,但随后更改为:
{
"1": {
"id": "ycC7km7A"
},
"2": {
"id": "hgF5D4es"
}
}相反,如果我设置了https://example.com/delete.php?index=2 -所以我想删除最后一个数组的元素-它会将其保存为:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
}
]最后一个结果是我每次删除元素时所需要实现的结果,因为我需要JSON数组语法保留为[...],而不是{...}。
我在PHP脚本中做错了什么?
发布于 2020-01-12 00:20:18
在PHP中对数组(关联或非关联)使用unset()将保留现有的键,使数组成为关联的。您需要在使用unset()后执行reindex the array
// delete the row with the index
unset($data_array[$index]);
$data_array = array_values($data_array);https://stackoverflow.com/questions/59696082
复制相似问题