如何在同一数组中嵌套JSON数据,然后再次进行JSON编码


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

我正试图通过$POST发送数据,并将数据传递和推送到数组中,然后写回json文件。我的问题是在数组推送中,我想我需要一个foreach来超越array_push,这样,当jsondata被写入文件时,然后在发送下一个$POST时重新移植该文件,它将全部嵌套在同一个json dict下。但正如你从我的check.json文件中看到的,我运气不好。提前感谢。。。

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

{}

当我运行它时,我返回的结果不在同一个JSON DICT中。

Check.json 的输出

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

我希望它看起来像这样:

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

使用+:连接表单数据数组和解码的JSON数组

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

或者只需添加新密钥:

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

或者,正如我认为另一个答案试图建议的那样,使用一个对象:

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

我希望这会有所帮助,但当您要做的是向对象添加属性时,您正在将项附加到数组中。

在"您想要的JSON"中,您显示了一个包含一个对象的数组,该对象具有两个属性321和88。这两个属性的值分别为"jake"answers"thomas"。

所以你可以只更改一行:

array_push($tempArray, $formdata);

它将一个项目添加到数组中,类似

$tempArray->$code = $cpu;

甚至

$tempArray[$code] = $cpu;

只需将属性和值附加到现有对象。

这允许您删除:

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

谢谢,Wayne