如何停止覆盖数组中的第一个索引

问题描述 投票:0回答:2

我在向阵列推送多个注释时遇到问题

当我提交评论时,它会覆盖前一个评论


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;
    }
}
php arrays json function array-push
2个回答
1
投票

如果要在函数内部改变后者,则需要将参数作为对原始数组的引用。如果您没有通过引用传递它,原始数组不会发生变异,并且您放置注释的副本将丢失,因为您没有返回它。

码:

function setComment (&$data) {...}

-1
投票

一个猜测:替换

array_push($data, $blogitem);

global $comments;
array_push($comments, $blogitem);

一个问题:这种封装是否必要?

$blogitem = [ "comment" => $comment ]; 
© www.soinside.com 2019 - 2024. All rights reserved.