【问题标题】:Append data to JSON array using PHP使用 PHP 将数据附加到 JSON 数组
【发布时间】:2014-09-18 15:41:43
【问题描述】:

我需要使用 PHP 将新对象附加到 JSON 数组。

JSON:

{
   "maxSize":"3000",
   "thumbSize":"800",
   "loginHistory":[
   {
      "time": "1411053987",      
      "location":"example-city"
   },
   {
      "time": "1411053988",      
      "location":"example-city-2"
   }
]}

到目前为止的 PHP:

$accountData = json_decode(file_get_contents("data.json"));
$newLoginHistory['time'] = "1411053989";
$newLoginHistory['location'] = "example-city-3";
array_push($accountData['loginHistory'],$newLoginHistory);
file_put_contents("data.json", json_encode($accountData));

在保存 JSON 文件时,我不断将“null”作为“loginHistory”对象的输出。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    问题是 json_decode 默认不返回数组,你必须启用它。看这里: Cannot use object of type stdClass as array?

    无论如何,只要在第一行添加一个参数就可以了:

    $accountData = json_decode(file_get_contents("data.json"), true);
    $newLoginHistory['time'] = "1411053989";
    $newLoginHistory['location'] = "example-city-3";
    array_push($accountData['loginHistory'],$newLoginHistory);
    file_put_contents("data.json", json_encode($accountData));
    

    如果您启用了 PHP 错误/警告,您会看到如下所示:

    致命错误:不能在 test.php 中使用 stdClass 类型的对象作为数组 在第 6 行

    【讨论】:

      【解决方案2】:

      $accountData 应该是一个对象。数组访问无效:

      array_push($accountData->loginHistory, $newLoginHistory);
      // or simply
      $accountData->loginHistory[] = $newLoginHistory;
      

      【讨论】:

      • 除了$newLoginHistory 应该是一个对象。
      • @AbraCadaver 如果它包含'字符串'键,它将在序列化时。
      【解决方案3】:

      这是一个关于如何使用 PHP 修改 JSON 文件的小而简单的指南。

      
      //Load the file
      $contents = file_get_contents('data.json');
      
      //Decode the JSON data into a PHP array.
      $contentsDecoded = json_decode($contents, true);
      
      //Create a new History Content.
      $newContent = [
        'time'=> "1411053989",
        'location'=> "example-city-3";
      ]
      
      //Add the new content data.
      $contentsDecoded['loginHistory'][] = $newContent;
      
      
      //Encode the array back into a JSON string.
      $json = json_encode($contentsDecoded);
      
      //Save the file.
      file_put_contents('data.json', $json);
      

      上面代码的逐步解释。

      1. 我们加载了文件的内容。在这个阶段,它是一个包含 JSON 数据的字符串。

      2. 我们使用函数 json_decode 将字符串解码为关联的 PHP 数组。 这允许我们修改数据。

      3. 我们向 contentsDecoded 变量添加了新内容。

      4. 我们使用 json_encode 将 PHP 数组编码回 JSON 字符串。

      5. 最后,我们修改了文件,用新创建的 JSON 字符串替换了文件的旧内容。

      【讨论】:

        猜你喜欢
        • 2011-12-15
        • 2018-12-20
        • 1970-01-01
        • 1970-01-01
        • 2017-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多