我在向阵列推送多个注释时遇到问题
当我提交评论时,它会覆盖前一个评论
include "includes/globals_constants.php";
$comments = [];
if (isset($_POST["commentSubmit"])) {
setComment($comments);
}
function setComment($data) {
$comment = htmlspecialchars($_POST["comment"]);
$blogitem = [
"comment" => $comment
];
array_push($data, $blogitem);
if (file_put_contents(DBCOMMENTS, json_encode($data, JSON_PRETTY_PRINT))) {
return true;
}
}
如果要在函数内部改变后者,则需要将参数作为对原始数组的引用。如果您没有通过引用传递它,原始数组不会发生变异,并且您放置注释的副本将丢失,因为您没有返回它。
码:
function setComment (&$data) {...}
一个猜测:替换
array_push($data, $blogitem);
同
global $comments;
array_push($comments, $blogitem);
一个问题:这种封装是否必要?
$blogitem = [ "comment" => $comment ];