[英]Using PHP to read and write to JSON
所以目前我正在開發一個需要使用PHP和JSON的項目。 我當前設置代碼的方式是使用file_get_contents讀取JSON文件,然后使用內置的json_decode()函數。 一切都在完美閱讀,而寫作部分卻給我帶來麻煩。
我設置JSON樹的方式是:
{
"test":[
{
"testName":"Winter 2011",
"testDate":"12/04/2011",
"testTime":"2:00pm",
"testRoom":"room",
"cap": 10,
"spotsLeft": 0,
"student":[
{
"fname":"Bob",
"lname":"Roberts",
"usrnm":"bobr",
"email":"bob@gmail.com"
}
]
}
]
}
為了得到正確的測試(因為將有多個測試)我正在使用foreach loop
,然后我確保沒有重復。 此時我已經准備好將新學生添加到JSON文件中,所以我打電話給:`
$file = file_get_contents('testDates.json');
$json = json_decode($file, true);
//Go through each test in the file
foreach ($json[test] as $t){
.....
//Works if I only do $t[student] but that only adds it to the $t[] and not the
//JSON file. Can't seem to get it to add to the whole JSON string.
array_push($json[$t][student], $newStudent);
echo json_encode($json);
.....
//Use a file_put_contents later to write the file out
任何想法都會非常有幫助。 這可能是指向數組中某個點的指針錯誤,但第二組眼睛從未受傷。 謝謝。
$t
是一個副本,它沒有引用原始對象。 這適用於每個foreach循環。 改為使用:
foreach ($json[test] as $k => $t){
array_push($json[test][$k][student], $newStudent);
...
}
或者您可以嘗試:
foreach ($json[test] as &$t){
array_push($t[student], $newStudent);
...
}
參見此處以了解foreach的工作原理: http : //php.net/manual/zh/control-structures.foreach.php
你在foreach中使用了錯誤的$ json [$ t]而不是$ json [“test”] [$ t],你還需要使用鍵值對
$testVal = $json["test"];
foreach ($testVal as $key => $val){
. . .
array_push($testVal[$key]["student"], $newStudent);
. . .
}
PS使用$ json ['test']而不是$ json [test],第一個引發語法警告,PHP將其解釋為字符串“ test”(在您的情況下,它是有效的:))
嘗試這個:
$json = json_decode($jsonString);
if($json["color"] == "blue"){
...
}
$json["language"] = "php";
$newJsonString = json_encode($json);
這不容易嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.