如何在JSON文件中添加子数组?

时间:2017-03-07 05:34:17

标签: arrays json

我有一个结果json文件,即result.json,我想在总数和行中插入另一个子数组。

这是我的JSON文件

{ “总”: “9”, “行”:[             {“id”:“16”,“firstname”:“Melanie”,“lastname”:“Toledo”,“phone”:“091919191”,“email”:“test@gmail.com”},{“id” :“29”,“firstname”:“x”,“lastname”:“x”,“phone”:“1”,“email”:“test@gmail.com”},{“id”:“30” ,“firstname”:“y”,“lastname”:“y”,“phone”:“2”,“email”:“test@gmail.vp”},{“id”:“31”,“firstname” :“xxx”,“lastname”:“xxxx”,“phone”:“12345”,“email”:“test@gmail.com”},{“id”:“33”,“firstname”:“xy” ,“lastname”:“xy”,“phone”:“1”,“email”:“test@gmail.com”},{“id”:“34”,“firstname”:“yyy”,“lastname” :“yyy”,“phone”:“2”,“email”:“test@gmail.com”},{“id”:“35”,“firstname”:“n”,“lastname”:“n” ,“电话”:“1”,“电子邮件”:“test@gmail.com”},{“id”:“36”,“firstname”:“q”,“lastname”:“q”,“phone” :“1”,“email”:“x @ g.com”},{“id”:“37”,“firstname”:“”,“lastname”:“”,“phone”:“”,“电子邮件“:”“}         ] }

这是我的代码

<?php
$current_data = file_get_contents('result.json');
$array_data = json_decode($current_data, true);
$extra['rows'] = array (
        'id'        =>  '101',
        'firstname' =>  'marlon',
        'lastname'  =>  'berces',
        'phone'     =>  '12',
        'email'     =>  'test@gmail.com'
        );
        $array_data[] = $extra;
        $final_data = json_encode($array_data);
        file_put_contents('result.json',$final_data);
?>

3 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,您需要在当前行列表中添加新行,之后,您必须更新总和,因为这是来自文件的所有静态数据。

<?php
// Read json
$current_data = file_get_contents('result.json');
$array_data = json_decode($current_data, true);

// New row
$extra = array(
    'id'        =>  '101',
    'firstname' =>  'marlon',
    'lastname'  =>  'berces',
    'phone'     =>  '12',
    'email'     =>  'test@gmail.com'
);

// Add the new row
$array_data['rows'][] = $extra;

// Update the sum
$array_data['total'] = count($array_data['rows']);

// Write json
$final_data = json_encode($array_data);
file_put_contents('result.json',$final_data);
?>

答案 1 :(得分:0)

你可以通过将其转换为数组然后使用array_push添加新值agani转换为json ...

答案 2 :(得分:0)

我认为你要找的是 Array.prototype.push()方法(在JavaScript中)。或者,如果您使用的是PHP,那么 array_push()

push()/ array_push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。