我有这个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'作为第二个参数,它将被解码为数组而不是对象。无需手动完成。 –