如何更新Json文件

时间:2014-06-13 07:24:10

标签: php android json webserver updates

谢谢大家的帮助和关注。我有一个从.json文件读取数据的应用程序,我的所有文件都位于远程服务器上。我需要做的是每次将新文件添加到文件夹时更新.json文件。

可以这样做,如果是这样的话怎么办?下面是我到目前为止一起编写的代码,用于读取文件夹中的内容并输出.json

if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
    if($file == "." or $file == ".."){
    } else {
        $return_array[] = $file; // Add the file to the array
    }
}

然后我回应了调查结果

}echo json_encode($return_array);

及以下是我需要更新的.json文件

{
"contacts": [
    {
            "id": "c200",
            "name": "http://allhiphoprandbandurbanmusicnetwork.com/ahrum_chat/uploads/Jun%205,%202014%206:53:15%20PMkasirisx@gmail.comfreestyle.mp4",
            "email": "ravi@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    }

    }
]

我是Php和.Json的初学者,所以任何帮助都会很棒。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我不确定您提供的代码以及它与.json文件的关系,但执行此操作的基本方法是:

  1. 将.json文件读入数组(Array1)
  2. 读取所有新文件并将其添加到新阵列(数组2)
  3. 合并Array2和Array1。
  4. 将合并的数组写入.json文件,覆盖所有内容。
  5. 编辑: 这是一个让你理解的例子,我可以用最简单的方式来理解它:

    /* users.json
    {
        data:[
                 {
                     first_name:"Lionel",
                     last_name:"Messi"
                 }
             ]
    }
    */
    
    // Read your .json file into an array
    
    $fileName = "users.json";
    $array = json_decode(file_get_contents($fileName), true);
    $arrayA = $array["data"];
    
    // Read and add new files into a new array
    
    ...
    ...
    $arrayB = array(array("first_name" => "Cristiano", "last_name" => "Ronaldo"));
    
    // Merge both arrays
    
    $arrayC = array_merge($arrayA, $arrayB);
    
    // Write to .json file again
    
    file_put_contents($fileName, json_encode(array("data" => $arrayC)));