我想通過$ POST發送數據,並且具有通過並推入陣列中的數據,然後寫回JSON文件。我的問題是在數組推進中,我想我需要一個foreach來超出array_push,這樣當jsondata被寫入文件,然後在下一個$ POST被髮送時重新導入該文件,它將全部嵌套在相同的json字典。但正如你可以從我的check.json文件中看到的,我沒有任何運氣。在此先感謝...如何在同一個數組中嵌套JSON數據,然後再次對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"}]
推陣列到陣列而不是要合併。 – Rizier123
它是一個使用編號鍵的粘性檢票,這意味着什麼,像array_merge這樣的東西會重新編號,如果他們不是字符串。array_merge ::'使用數字鍵輸入數組中的值將使用結果數組中從零開始的遞增鍵重新編號。 ' – ArtisticPhoenix
只需將它添加到現有數組'$ tempArray [$ code] = $ cpu'中,獲取嵌套數組的原因是因爲您正在將數組推到末尾或其他數組''tempArray' – ArtisticPhoenix