【问题标题】:Append javascript object to json file with php使用 php 将 javascript 对象附加到 json 文件
【发布时间】:2016-06-02 04:12:11
【问题描述】:

我有这个任务,我用一个表单创建一个 js 对象,然后将这个数据保存到一个 json 文件中。我目前拥有的是执行此操作的代码,如果文件已经存在,则将新数据附加到文件中。唯一的问题是数据被附加为一个数组,但我需要它作为一个对象附加到一个主数组中。

这是输出(示例)

[
  [
    {
        "campaignId": "campaign1",
        "id": "c1"
    }
  ],
  [
    {
        "campaignId": "campaign2",
        "id": "c2"
    }
  ]
]

但我需要的是

[
  {
     "campaignId": "campaign1",
     "id": "c1"
  },
  {
     "campaignId": "campaign2",
     "id": "c2"
  }
]

我不是 php 开发人员,所以我的 php 知识相当有限,我正在谷歌搜索完成这项任务,但我已经到了 google 让我失望的地步。

这是我的 php 代码

<?php

$json = $_POST['json'];
$name = $_POST['name'];
$cat = $_POST['category'];

// make requested directory
// to see if directory exists

$filename = "savedData/$cat/";

if (file_exists($filename)) {
   //echo "The directory {$dirname} exists";
} else {
   mkdir($filename, 0777);
   echo "The directory {$dirname} was successfully created.";
}

$file = "savedData/$cat/$name.json";

// Append new form data in json string saved in text file

$json = json_decode($json);

$formdata = array(
  $json
);

$arr_data = array();        // to store all form data

// check if the file exists
if(file_exists($file)) {
  // gets json-data from file
  $jsondata = file_get_contents($file);

  // converts json string into array
  $arr_data = json_decode($jsondata, true);
}

// appends the array with new form data
$arr_data[] = $formdata;

// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

// saves the json string in $file
// outputs error message if data cannot be saved
if(file_put_contents($file, $jsondata)) echo 'Data successfully saved';

?>

我热衷于如何解决这个问题,更重要的是了解如何解决这个问题以获得所需的输出,任何帮助都会很棒:)

【问题讨论】:

    标签: php arrays json object


    【解决方案1】:

    $json 在这里放入一个数组中

    $formdata = array(
      $json
    );
    

    然后你把它放在另一个数组里

    $arr_data[] = $formdata;
    

    相当于

    $arr_data = array(
      array($json)
    );
    

    试试这个:

    $arr_data[] = $json; 
    

    【讨论】:

    • 太棒了,太简单了! :) 谢谢,只要你知道怎么做就容易了
    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 2019-04-29
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2011-12-15
    相关资源
    最近更新 更多