如何使用 PHP 更新 JSON 文件中的值


How to update a value in a JSON file using PHP

我正在尝试更新 json 文件中其中一个对象的值。问题是同一个 json 文件中有几个具有相同键值对的同级。

我的 JSON 文件如下所示:

{"LogIns":[
{"Username":"Alfred",
"password":"123",
"Won":0,"Lost":0},
{"Username":"Farrah",
"password":"123",
"Won":0,"Lost":0}]}

每次有人赢了一手牌(这是一个纸牌游戏),我都需要更新赢或输的游戏数量。

这是对 PHP 文件的 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;
    }
}