鍍金池/ 問答/Java  PHP/ 如何使用PHP添加數(shù)據(jù)到JSON文檔中的指定對(duì)象中

如何使用PHP添加數(shù)據(jù)到JSON文檔中的指定對(duì)象中

想知道生成一組json后,利用file_put_contents添加到了指定的sncode.json中后,
如何添加到文檔中指定的對(duì)象中去
eg:

{"sncode":[
    {"model":"666","sncode":"2333333"},
    {"model":"666","sncode":"1234569"},
    {...}
]}

目前我添加新的json進(jìn)去只會(huì)一直是

    {"model":"666","sncode":"2333333"},{"model":"666","sncode":"1234569"}    
    {"model":"666","sncode":"1234569"}{"model":"666","sncode":"1234569"}

因?yàn)閖son從第二個(gè)開始寫,格式就錯(cuò)亂了,導(dǎo)致我無論如何都無法正確的讀取到JSON信息

回答
編輯回答
葬愛

讀取 : $cont = file_get_content($file);
解碼: $info = json_decode($cont, true);
添加: $info['sncode'][] = ['model'=>'666','sncode'=>'123'];
編碼: $json = json_encode($info);
寫入: file_put_content($json);

2018年3月31日 22:03
編輯回答
乞許

讀取,解碼,添加,編碼,寫入

2018年2月2日 18:16