所以我有一个由mysql查询生成的json对象数组。
json对象看起来像:
[
{"field1": "value1", "field2": "value2"},
{"field1": "value3", "field2": "value4"},
{"field1": "value5", "field2": "value6"},
{"field1": "value7", "field2": "value8"}
]
现在我想添加如下空对象: {}
在数组中的第三个json对象之后。
预期结果:
[
{"field1": "value1", "field2": "value2"},
{"field1": "value3", "field2": "value4"},
{"field1": "value5", "field2": "value6"},
{},
{"field1": "value7", "field2": "value8"}
]
我能够遍历每个json对象,并且能够替换当前对象的值,但不确定如何添加一个全新的json空对象。
我的代码
for($j = 0; $j < $length; $j++) {
if($j == 1 ){
// HERE I dont want to replace Jth JSON Obj but add new empty Obj, something like $data.push('{}')
$data[$j]['field1'] = '';
$data[$j]['field2'] = '';
}else{
$data[$j]['question'] = $ques_arr[$j];
$data[$j]['response'] = $allresponses[$j]['response'];
}
}
2条答案
按热度按时间t1qtbnec1#
尝试通过
new \StdClass()
或者[(object)[]]
作为例子返回
[{"field1":"value1","field2":"value2"},{"field1":"value3","field2":"value4"},{},{"field1":"value7","field2":"value8"}]
更新使用array_splice()
并尝试:如你所愿。
oxosxuxt2#