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

时间:2016-04-26 07:18:45

标签: javascript php json ajax

我试图更新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总是(&#34; 1&#34;),但是当我print_r $ json时,赢或输的字段仍为0.

有人知道我做错了吗?

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

很快:您正在更新未引用原始数组元素的临时项$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;
    }
}