首頁  >  問答  >  主體

json_decode 在 .json 檔案中儲存 2 個陣列後傳回 null - 驗證

我有一個關於 PHP 與 JSON 結合使用的問題。

我使用陣列來儲存 .json 檔案內部。包含資料的陣列來自我的index.php,並由使用者填充,到目前為止一切順利。所有內容都保存在 .json 中,當我有超過 1 個用戶在其中存儲內容時(意味著 .json 文件中有 2 個數組),它不會返回數據,而是返回 NULL。我是否遺漏了有關保存或讀取 JSON 文件的內容?我發現我的 JSON 無效,它在驗證器內向我顯示“多個根 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 迴圈內):

$lists[]= [
                "count"=>$count,
                "name"=>$name
            ];
        }

    }

    $lists[]= [
        "info" => $number
    ];

有沒有一種方法可以像這樣驗證它,這樣解碼就不會回傳 null?

P粉333395496P粉333395496218 天前351

全部回覆(1)我來回復

  • P粉724256860

    P粉7242568602024-02-18 00:20:20

    一個陣列下的另一個陣列是無效的 JSON。您應該使用一個根數組並將您的用戶保留在其中(不確定數組中的內容是否有意義,但您明白了):

    [
        [{"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}]
    ]
    

    換句話說,應該如下所示:

    1. 用戶發送表單
    2. 您已閱讀文件內容
    3. 您可以使用 json_decode() 對其進行解碼
    4. 您加入到陣列
    5. 您可以使用 json_encode() 將其編碼回來
    6. 您將整個新 JSON 儲存到檔案中,取代舊內容

    回覆
    0
  • 取消回覆