0
我試圖更新json文件中某個對象的值。問題是在同一個json文件中有幾個同名鍵值對的兄弟姐妹。如何使用PHP更新JSON文件中的值
我的Json文件看起來像這樣:
{"LogIns":[
{"Username":"Alfred",
"password":"123",
"Won":0,"Lost":0},
{"Username":"Farrah",
"password":"123",
"Won":0,"Lost":0}]}
每次有人贏得了手(這是一個紙牌遊戲),我需要更新的遊戲數量贏或輸。
這是AJAX調用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
有誰知道我做錯了什麼?
任何幫助將永遠不勝感激。
感謝
爲什麼使用'突破; '?還沒有在if-else語句中看到過。 –
@JeroenBellemans它突破了'foreach'循環 –
是的,做了一些研究,以後可能會有用:)謝謝 –