mysql—在预先存在的json对象中以及给定json对象索引之后添加空json对象—php

lmvvr0a8  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(288)

所以我有一个由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'];
            }
        }
t1qtbnec

t1qtbnec1#

尝试通过 new \StdClass() 或者 [(object)[]] 作为例子

$test = '[
{"field1": "value1", "field2": "value2"},
{"field1": "value3", "field2": "value4"},
{"field1": "value5", "field2": "value6"},
{"field1": "value7", "field2": "value8"}
]';
 $temp = json_decode($test);
 array_splice($temp, 3, 0, new \StdClass());
$result = json_encode($temp);
var_dump($result);

返回 [{"field1":"value1","field2":"value2"},{"field1":"value3","field2":"value4"},{},{"field1":"value7","field2":"value8"}] 更新使用 array_splice() 并尝试:

$test = '[
{"field1": "value1", "field2": "value2"},
{"field1": "value3", "field2": "value4"},
{"field1": "value5", "field2": "value6"},
{"field1": "value7", "field2": "value8"}
]';
    $temp = json_decode($test);
    $value = (new \StdClass());
    array_splice($temp, 3, 0, [(object)[]]);
    $result = json_encode($temp,true);
    var_dump($result);

如你所愿。

oxosxuxt

oxosxuxt2#

$json = '[
    {"field1": "value1", "field2": "value2"},
    {"field1": "value3", "field2": "value4"},
    {"field1": "value5", "field2": "value6"},
    {"field1": "value7", "field2": "value8"}
    ]';
    $temp = json_decode($json);
    $inserted = array( (object)[]);
    array_splice( $temp, 3, 0, $inserted );
    $result = json_encode($temp);
    var_dump($result);

相关问题