使用PHP将数据附加到JSON数组中

问题描述 投票:3回答:3

我需要使用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
3个回答
2
投票

$accountData是应有的对象。数组访问无效:

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

3
投票

问题是,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错误/警告,您将看到如下所示:

致命错误:无法将stdClass类型的对象用作test.php中的数组在第6行


0
投票

这是有关如何使用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. 我们向contentDecoded变量添加了新内容。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.