我有这个JSON对象数组类型数据,我想用键插入数组。如果我做print_r,数据如下:
[{"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中应该很容易。
任何想法和帮助都非常感激。
答案 0 :(得分:1)
您正在更新整个阵列,您需要的是向阵列添加项目,因此您需要[]
。变化
$formdata = array('..........
到
$formdata[] = array('......
答案 1 :(得分:0)
尝试以下
您需要更改 $ formdata 至 $ formdata []
<强>替换强>
foreach($data as $value){
$formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);
}
。通过强>
foreach($data as $value){
$formdata[] = array('comment' => $value->comment, 'date_created' => $value->datecreated);
}
答案 2 :(得分:0)
更改此
foreach($data as $value){
$formdata = array('comment' => $value->comment, 'date_created' => $value->datecreated);}
到这个
foreach($data as $value){
$formdata[] = array('comment' => $value->comment, 'date_created' => $value->datecreated);}
问题在于在每次迭代中将新数组分配给同一个变量而不是向现有数组添加新项