我有一個關(guān)於 PHP 與 JSON 結(jié)合使用的問題。
我使用陣列來儲存 .json 檔案內(nèi)部。包含資料的陣列來自我的index.php,並由使用者填充,到目前為止一切順利。所有內(nèi)容都保存在 .json 中,當(dāng)我有超過 1 個用戶在其中存儲內(nèi)容時(意味著 .json 文件中有 2 個數(shù)組),它不會返回數(shù)據(jù),而是返回 NULL。我是否遺漏了有關(guān)保存或讀取 JSON 文件的內(nèi)容?我發(fā)現(xiàn)我的 JSON 無效,它在驗證器內(nèi)向我顯示“多個根 JSON 元素”。
這是我寫和讀取 .json 的程式碼:
public function JSONwrite($lists) { $listFill = json_encode($lists)."\n"; file_put_contents("/var/www/html/3sprint/test.json",$listFill,FILE_APPEND); } public function JSONread() { $string = file_get_contents("/var/www/html/3sprint/test.json"); $stringContent = json_decode($string, true); var_dump($stringContent); }
我的 JSON 檔案看起來像這樣(填滿了 2 個陣列):
[{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}] [{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}]
這是我填入陣列的地方,然後將其傳遞給 JSONwrite 方法(這是在 foreach 迴圈內(nèi)):
$lists[]= [ "count"=>$count, "name"=>$name ]; } } $lists[]= [ "info" => $number ];
有沒有一種方法可以像這樣驗證它,這樣解碼就不會回傳 null?
一個陣列下的另一個陣列是無效的 JSON。您應(yīng)該使用一個根數(shù)組並將您的用戶保留在其中(不確定數(shù)組中的內(nèi)容是否有意義,但您明白了):
[ [{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}] [{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}] ]
換句話說,應(yīng)該如下所示:
json_decode()
對其進(jìn)行解碼json_encode()
將其編碼回來