我有這個JSON對象數組類型數據,我想插入數組與鍵。如果我做print_r的,視爲該數據如下:插入對象數據到數組PHP
[{"comment":"hola hi ","datecreated":"2017-02-27 13:53:25"},{"comment":"hola hi harambeh ","datecreated" :"2017-02-27 13:53:30"}]
這裏是我的相關代碼:
$data = json_decode($_REQUEST['array']);
$formdata = [];
foreach($data as $value){
$formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);
}
然而,結果數組只用了最後一個對象,這是
Array
(
[comment] => hola hi harambeh
[date_created] => 2017-02-27 13:53:30
)
很明顯,我需要每一項數據,而不僅僅是最後一項。這在JavaScript中應該很容易。
任何想法和幫助非常感謝。
在foreach循環中使用'$ formdata []'並且不需要在新數組中插入,因爲如果使用'json_decode($ _ REQUEST ['array'],true)'給出array read [manual]( http://php.net/manual/en/function.json-decode.php) – gaurav
你應該閱讀[手冊](http://php.net/manual/en/function.json-decode.php) 'json_decode()'。只需傳遞'true'作爲第二個參數,它將被解碼爲數組而不是對象。無需手動完成。 –