我正在尝试更新 json 文件中对象之一的值。问题是同一个 json 文件中有多个具有相同键值对的同级。
我的 Json 文件如下所示:
{"LogIns":[
{"Username":"Alfred",
"password":"123",
"Won":0,"Lost":0},
{"Username":"Farrah",
"password":"123",
"Won":0,"Lost":0}]}
每次有人赢得一手牌(这是一场纸牌游戏)时,我都需要更新获胜或失败的游戏数量。
这是对 PHP 文件的 AJAX 调用:
<小时/>AJAX:
var username = localStorage.getItem("username");
if(document.getElementById(btnId).value == answer){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
console.log("returned:", xhttp.responseText);
}
xhttp.open("POST", "leaderboard.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username + "&won=1");
}
else{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
console.log(xhttp.responseText);
}
xhttp.open("POST", "leaderboard.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username + "&lost=1");
}
setTimeout(reloadPage, 2000);
}
你可以相信我的话,HTML 是完全正确的,这里并不真正需要,但我的 PHP 文件看起来像这样:
PHP:
<?php
$username = $_POST['username'];
if(isset($_POST['won'])){
$won = $_POST['won'];
//echo $won;
}
if(isset($_POST['lost'])){
$lost = $_POST['lost'];
//echo $lost;
}
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
foreach($json['LogIns'] as $res){
if($res['Username']==$username){
if(isset($won)){
$add = $res['Won'];
$add = ($add + $won);
$res['Won'] = $add;
echo $res['Won'];
}
else{
$add = $res['Lost'];
$add = ($add + $lost);
$res['Lost'] = $add;
echo $res['Lost'];
}
break;
}
}
file_put_contents('logins.json', json_encode($json));
?>
打印到屏幕上的 xhttp.responseText
始终为(“1”),但是当我 print_r $json 时,赢或输字段仍然为 0。
有人知道我做错了什么吗?
任何一如既往的帮助将不胜感激。
谢谢
最佳答案
简而言之:您正在更新一个不引用原始数组元素的临时项$res
。在 PHP 中,默认情况下仅通过引用传递对象。如果您想通过引用传递另一个变量类型,则必须在其前面添加 &
。
更多详细信息请参见:http://php.net/manual/en/control-structures.foreach.php
快速修复,未经测试:
foreach ($json['LogIns'] as $index => $res) {
if ($res['Username'] == $username) {
if (isset($won)) {
$add = $res['Won'];
$add = ($add + $won);
$json[$index]['Won'] = $add; // <-
echo $res['Won'];
}
else{
$add = $res['Lost'];
$add = ($add + $lost);
$json[$index]['Lost'] = $add; // <-
echo $res['Lost'];
}
break;
}
}
或者您可以通过引用将数组项传递给循环:
foreach ($json['LogIns'] as &$res) { // <-
if ($res['Username'] == $username) {
if (isset($won)) {
$add = $res['Won'];
$add = ($add + $won);
$res['Won'] = $add;
echo $res['Won'];
}
else{
$add = $res['Lost'];
$add = ($add + $lost);
$res['Lost'] = $add;
echo $res['Lost'];
}
break;
}
}
关于javascript - 如何使用 PHP 更新 JSON 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857893/