我有一个视频ID数组,当用户单击某个按钮时,点击的视频的videoId会附加到该数组。PHP-JSON在取消设置值时保存为错误格式
当用户再次点击同一按钮时,代码搜索videoId,如果找到,则从阵列中删除视频ID。
数组保存在一个JSON文件,其格式为["aaa","bob"...]
然而,当我从阵列中删除一个值的JSON文件转化为{"1":"aaa", "2":"bbb"...}
我怎样才能防止这种情况发生?
PHP:
$NameFileJSON = $_GET["NameFile"];
$VideoId = $_GET["VideoId"];
$removeVideoId = $_GET["RemoveVideoId"];
$results = array($VideoId);
SAVE VIDEOID:
if (($NameFileJSON != "")&&($VideoId != "")&&($removeVideoId == "")){
$filename = "json/likesJSON/$NameFileJSON.json";
if (file_exists($filename)) {
echo "The file $filename exist";
$inp = file_get_contents("json/likesJSON/$NameFileJSON.json");
$arr = json_decode($inp);
array_push($arr, $results[0]);
$fp_login = fopen("json/$NameFileJSON.json", w);
fwrite($fp_login, json_encode($arr));
fclose($fp_login);
} else {
echo "The file $filename does not exist";
$fp_login = fopen("json/$NameFileJSON.json", w);
fwrite($fp_login, json_encode($results));
fclose($fp_login);
}
}
DELETE VIDEOID:
if (($NameFileJSON != "")&&($VideoId == "")&&($removeVideoId != "")){
$inp = file_get_contents("json/$NameFileJSON.json");
$arr = json_decode($inp);
if (($index = array_search($removeVideoId, $arr)) !== false) {
echo $index;
unset($arr[$index]);
}
$fp_login = fopen("json/$NameFileJSON.json", w);
fwrite($fp_login, json_encode($arr));
fclose($fp_login);
}
print_r(json_encode($arr)
你尝试'方法Array.splice()'在JavaScript中,而不是'delete'?或者,删除是什么意思? – PHPglue
它是php方面的行为。 'array_values'可以在这里帮助.. –