我在向数组推送多个注释时遇到问题
我提交评论时,它会覆盖前一个评论
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;
}
}
答案 0 :(得分:1)
如果要在函数中对后者进行突变,则需要使用参数作为对原始数组的引用。如果您不通过引用传递它,则原始数组不会发生变异,并且您放入注释的副本也会丢失,因为您不返回它。
代码:
let originalWidth = img.width;
let originalHeight = img.height;
let lastScale = 1;
for (let percent = 100; percent >= 10; percent -= 5) {
let percentScale = percent / 100;
let adjustedScale = percentScale / lastScale;
lastScale = percentScale;
let ctx = img.getContext("2d");
ctx.scale(adjustedScale, adjustedScale);
...
答案 1 :(得分:-1)
一个猜测:替换
array_push($data, $blogitem);
与
global $comments;
array_push($comments, $blogitem);
一个问题:这种封装是否必要?
$blogitem = [ "comment" => $comment ];