在PHP中删除JSON数组元素,然后重新编码为JSON
问题描述:
function deleteNews($selected) {
$file = file_get_contents('news.json', true);
$data=json_decode($file,true);
unset($file);
foreach($selected as $index){
unset($data[$index]);
}
$result=json_encode($data);
file_put_contents('news.json', $result);
echo $result;
unset($result);
$url="./deleteNews.php";
//redirect($url);
}
上面的功能应该从JSON中删除一个条目,例如:
The above function is supposed to delete an entry from a JSON like :
[
{
"dummy":"dummy",
"dummy1":"dumy"
},
{
"dummy":"dummy1",
"dummy1":"dummy"
}
]
但是最后该函数在JSON中插入数字索引,这是不希望的.
But in the end the function inserts numerical indexes in the JSON, which is not desirable.
结果就像
[
"0":
{
"dummy":"dummy",
"dummy1":"dumy"
},
"1":
{
"dummy":"dummy1",
"dummy1":"dummy"
}
]
如何从中获取我的原始JSON格式?我不要那个0 1 2索引部分.
How can I get my original JSON format from this? I don't want that 0 1 2 index part.
N.B:是foreach
来完成的.如果没有foreach
,则将按预期方式创建JSON.
N.B: it's the foreach
that does this. Without the foreach
, the JSON is created as expected.
答
尝试使用array_values:
Try it with array_values:
$result = json_encode(array_values($data));