Jason Owens Jason Owens - 3 months ago 5
JSON Question

How can I nest JSON data within same array and then json encode again?

I'm trying to send data via $POST, and have that data passed and pushed into the array, then written back to the json file. My problem is coming within the array push, I think I need a foreach to go above array_push, that way when jsondata is written to the file and, then reimporting that file when the next $POST is sent, it'll all be nested under the same json dict. But as you can see from my check.json file, I'm not having any luck. Thanks in advance...

test11.php

<?php
$code = $_POST['code'];

$cpu = $_POST['cpu'];

$formdata = array($code=> $cpu);

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp, true);
array_push($tempArray, $formdata);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
echo "This is the formdata = $formdata";
echo "This is the inp = $inp";
echo "This is the jsonData = $jsonData ";

?>


t11.html

<form action="test11.php" method="POST">
CPU Name:<br>
<input type="text" name="cpu">
<br><br/>
Code:<br>
<input type="text" name="code">
<br><br>
<input type="submit" value="Submit">
</form>


check.json

{}


When I run it, my results returned are not in the same JSON DICT.

Output of Check.json

[{"321":"jake"},{"88":"thomas"}]


I'm wanting it to look like this:

[{321:"jake",88:"thomas"}]

Answer

Join the form data array and the decoded JSON array using +:

$tempArray = $tempArray + $formdata;
$jsonData  = json_encode($tempArray);

Or just add the new key:

$tempArray[$code] = $cpu;
$jsonData  = json_encode($tempArray);

Or as I think the other answer is trying to suggest, use an object:

$tempObj = json_decode($inp);
$tempObj->$code = $cpu;
$jsonData = json_encode($tempObj);
Comments