我试图将用户“最喜欢的”游戏发布到用户的相应文件中。
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
该文件的结构如下:
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
}
]
目前它将添加正确的数据,但不是添加到数组中,而是添加到最后。
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
},
{
"CNR": {
"favourite": "game"
}
}
]
我尝试过arraypush,splice和其他方法,但我不确定这个用例最好的是什么。非常感谢您对如何以最佳效果实现这一目标的任何想法/建议,谢谢!
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
区别在于我将[]
移动到了$arr_data
的末尾。
在将其添加到阵列之前,您需要检查密钥是否存在,然后继续而不是仅添加代码。
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
// changes over here
if(isset($arr_data[$_SESSION['username']])){
if(isset($arr_data[$_SESSION['username']]['favourite'])){
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
} else {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
} else {
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
}
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
我可以看到大多数人已回答了这个问题,但我是否也可以为您的流程提供一些建议(值得深思)?
1)。首先,如果您将所有用户存储在一个文件中,或者每个用户都有一个文件,我就无法解决问题。示例username.json我将假设每个用户名都有一个文件,因为应该更快地进行文件写入,并且需要为其他人锁定主文件,因为一个用户正在写入它。
2)。我注意到最喜欢的部分似乎也存储在_SESSION中。如果_SESSION在其中存储了相同的迷你数组(存储在文件中的副本),则打开文件写入单个值然后再次保存是没有意义的。您也可以直接写下现有文件。像这样...
$writeToFile = json_encode($_SESSION[mydata]);
$fh = fopen("/path/to/username.json","w+");
fwrite($fh,$writeToFile);
fclose($fh);
// You could also use file_put_contents but most prefer
// to use fopen()
3)。我将假设您存储的密码已加密,没有人可以键入[yourdomain] /users/username.json来查看json文件的原始输出。您可能希望确保无法从浏览器访问.json文件。你可以用.htaccess做到这一点。
问题在于此代码,每次创建新的子数组时都要创建:更改此:
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
对此
if(isset($arr_data[$_SESSION['username']])) {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}