PHP - 存储,更新和读取数组的最佳方法?

<?php

$boxes = array
(
    array("box1","w","pink"),
    array("box2",".", "aqua")
);

if(isset($_POST['getBoxI'])) {
    $ind = $_POST['getBoxI'];
    echo $boxes[$ind][0].','.$boxes[$ind][1].','.$boxes[$ind][2].',';
}

if(isset($_POST['setBoxI'])) {
    $ind = $_POST['setBoxI'];
    $fill = $_POST['setBoxFill'];
    $col = $_POST['setBoxCol'];
    $boxes[$ind][1] = $fill;
    $boxes[$ind][2] = $col;
    echo $boxes[$ind][0].','.$boxes[$ind][1].','.$boxes[$ind][2].',';
}

?>

basically I'm trying to build a site where different users can click boxes and enter information, and the boxes update in "real time" whenever someone changes the information of the box such as the text, or background color. that information gets sent to the server when the form gets filled. The form gets sent via jQuery Posting using the 'setBoxI' key. The client updates the page every X seconds by jQuery Posting to this php file, using the 'getBoxI' key.

The problem is that even if you update the array using the setBoxI key, the next time you use getBoxI, the array is back to the defaults shown ("box1", "w","pink") instead of the values that the user entered.

So obviously this isn't the best way to store this kind of data. I believe it is because everytime this php file gets called, it opens a new copy of the file which has the default array entered, instead of the array that the user created via the setBoxI key.

What would be a better way to accomplish this while only using nginx, jquery, and php?

Another design choice would be to use jQuery AJAX. You can code this so that every key press, mouse click or timer event causes data to be sent asynchronously to your server.

Data can be sent to your server and your server can return the combined data from all the users.

A very simple example is loading a file from your server into an HTML control on a button click:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url: "demo_test.txt", success: function(result){
            $("#div1").html(result);
        }});
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

It seems that you have to store your boxes data somewhere between requests. Possible approches are using database, files, some cache engine, network storage and so on.

Probably the easisest way to start with is to store serialised data to file. Read them like this:

$boxes = json_decode(file_get_contents('boxes'));

In the beginning of your code and store like this:

file_put_contents('boxes', json_encode($boxes));

After user updates them.

But you have to mind security, concurrency, performance and other issues, which can be effectively solved by using database.