Jason Owens Jason Owens - 2 months ago 4x
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...


$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 ";



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



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

Output of Check.json


I'm wanting it to look like this:



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);