0

I have the following PHP code, which gets executed when I hit the Submit button in a form:

// Save data
if(isset($_POST['save'])){

        $newDataArr = array();

        foreach ($data_array[0] as $k=>$v){

            $newDataArr[] = array($k => $_POST[$k]);

        }// ./ foreach

        echo json_encode($newDataArr);
}

The echo I get is the following:

[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]

Then I'll have to add that array into my JSON file as it follows:

$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);

But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:

{"ID->id":"esKZSCDfIC"},

must become:

"ID->id":"esKZSCDfIC",

Is there a way to dynamically create a valid JSON array and push it to my Test.json file?

I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.

Frank Eno
  • 2,581
  • 2
  • 31
  • 54
  • 1
    Read the json file, run `json_decode()` on it to make it a valid PHP data structure, add you new info to it, then convert it back to a jsonString `json_encode()` the new structure then write it to a file – RiggsFolly Jan 27 '20 at 13:35

1 Answers1

2

Instead of creating and pushing a new array on each iteration, set the values this way:

$newDataArr[$k] = $_POST[$k];

Hope this helps.

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23