iamleeadamson
iamleeadamson

Reputation: 39

Append javascript object to json file with php

I have this task where i create a js object with a form and then save this data to a json file. What I have at the moment is code that does this and appends new data to the file if the file already exists. The only problem is the data is appended as an Array but i need it to append as an object in one main array.

this is the output (example)

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

but what i need is

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

I am not a php developer so my php knowledge is fairly limited and i'm googling my way through this task but i have come to a point where google is failing me.

here is my php code

<?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';

?>

I am keen on how to fix this and more importantly understand how to fix this to get the desired output, any help would be awesome :)

Upvotes: 1

Views: 93

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32392

$json is put inside an array here

$formdata = array(
  $json
);

And then you put it inside another array here

$arr_data[] = $formdata;

which is equivalent to

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

Try this instead:

$arr_data[] = $json; 

Upvotes: 1

Related Questions