我的PHP代码遇到了一个奇怪的问题(我是PHP的初学者,所以对我糟糕的编码技巧表示歉意)。我的JSON中的每个数组项都有一个与之关联的唯一ID,删除一个数组我只是将唯一ID传递给我的代码,它删除与之关联的数组项,但是我的所有数组项都包含一个整数字段,并且没有t被删除,它弄乱了我的JSON(解析失败,当我稍后尝试这样做)。
<?php
$var1 = filter_input(INPUT_POST, 'unique_id', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "unique_id" parameter is not set');
}
$data = file_get_contents('feed.json');
if ($data === false) {
die('An error occurred when opening "feed.json"');
}
$json = json_decode($data, true);
if ( ! isset($json[0]['unique_id'])) {
die("The JSON was not decoded correctly");
}
foreach ($json as $key => $value) {
if ($value['unique_id'] == $var1) {
unset($json[$key]);
}
}
$new_json_string = json_encode($json);
file_put_contents('feed.json', $new_json_string, JSON_UNESCAPED_SLASHES | LOCK_EX);
echo "Success";
?>
以下是JSON示例:
[
{"student_id":"22222222","unique_id":"862916786a1340afbfdf23caa541963f","status":"Hey yo what's up","image":"none","likes":"0"},
{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"none","likes":22}
]
删除后,我留下了
{"1":{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"","likes":31}
正如您所看到的,{"1":
无效,不应该存在。
有谁知道我做错了什么?
编辑:这是我在JSON中创建新数组项目的代码
$json = file_get_contents('feed.json');
$data = json_decode($json);
$data[] = array('student_id' => "$student_id", 'unique_id' => "$unique_id" ,'status' => "$status_txt", 'image' => "$image_link", 'likes' => "0");
file_put_contents('feed.json', json_encode($data), JSON_UNESCAPED_SLASHES | LOCK_EX);
答案 0 :(得分:1)
这是两件事的组合:
JSON的[]
数组只能以逗号分隔的连续元素列表从索引0开始。
这两件事都存储为PHP的数组类型。 JSON对象使用关联键。
当你从数组中取消设置索引0时,它变得稀疏。现在,对JSON中具有something[1]
但没有something[0]
的内容进行编码的唯一方法是使对象具有键"1"
。
PHP的JSON编码器允许这样做,因为传入的数组是要被序列化为JSON对象的正确类型(数组)。所以它就是这样做的。
也许您想使用array_splice
删除数组元素而不是unset
。
答案 1 :(得分:0)
使用 array_values()来转换由Cheery在评论中通知的数组。