使用PHP将JSON数据附加到位于服务器上的JSON文件中


Append JSON Data to JSON File Located on Server with PHP

我的服务器上存储了一个JSON文件,我需要向其中添加数据。我已经成功地将该文件检索到内存中,并成功地对其进行了解析。我只是很难将新的JSON数据放在正确的位置。

以下是我的JSON文件的格式:

{
  "emails": [
              {
                "group": "1st Group",
                "list": [
                          {
                            "id": 1,
                            "subject": "Testing 1"
                          },
                          {
                            "id": 2,
                            "subject": "Testing 2"
                          }
                        ] // End list array
              }, // End 1st Group 
              {
                "group": "2nd Group",
                "list": [
                          {
                            "id": 3,
                            "subject": "Testing 3"
                          },
                          {
                            "id": 4,
                            "subject": "Testing 4"
                          }
                        ] // End list array
              } // End 2nd Group
              /* NEED TO INSERT NEW DATA HERE */
             ] // End emails array
}

我正在尝试在最后一个group list之后附加一个新的group list。在本例中,它将位于以下行之后:} // End 2nd Group

以下是我的PHP代码,它从服务器获取JSON文件并对其进行解析:

$getJSON = file_get_contents('emails.json');
$tempArray = json_decode($getJSON, true);
$numberOfGroups = count($tempArray['emails'][0]);

这是我的php代码,它创建了JSON文件的格式/布局:

$groupArray = array();
$json = array( 'emails' => array() );
foreach ($contextIORequest->getData() as $message) {
  $newTZ = new DateTimeZone("America/Chicago");
  $currentTime = new DateTime();
  $currentTime = DateTime::createFromFormat('U', $message['date_received']);
  $currentTime->setTimezone($newTZ);
  $formattedDateReceived = $currentTime->format('F j, Y');
  if (!in_array($formattedDateReceived, $groupArray)) {
      array_push( $json['emails'],
          array(
               'group' => $formattedDateReceived,
               'list' => array()
          )
      );
      $groupArray[] = $formattedDateReceived;
  }
  $body = str_replace(array("'r'n","'n"),"", $message['body'][0]['content']);
  $newBody = preg_replace('!'s+!', ' ', $body);
  array_push($json['emails'][array_search($formattedDateReceived,$groupArray)]['list'],
      array(
        'id' => $message['message_id'],
        'subject'=> addslashes($message['subject']),
        'to' => array("Me"),
        'body' => $newBody,
        'time' => $formattedDateReceived,
        'datetime' => $formattedDateReceived,
        'from' => $message['addresses']['from']['name'],
        'dp' => "assets/img/profiles/avatar.jpg",
        'dpRetina' => "assets/img/profiles/avatar2x.jpg"
      )
  );
} // end foreach loop
// Output the JSON
header('Content-Type: application/json');
echo json_encode($json);

那么,我该如何在最后一个group list之后添加一个新的group list呢?这需要在不包含用于创建JSON的emails数组的情况下完成。

在序列化数据上运行json_decode之后(第二个参数像您所做的那样作为true传递),在PHP中,您将获得一个关联数组,该数组在名为emails的键处有一个元素。该元素是一个数组,包含要向其中添加另一个的组列表。所以这是一个问题:

$data = json_decode($getJSON, true);
$data['emails'][] = $TheNewGroupList;

不要让它一开始是JSON格式的序列化数据这一事实让你疲惫不堪。一旦运行了json_decode,它就只是一个PHP数据结构(对象或数组),对它的操作就像任何其他PHP数据一样。