【问题标题】:How to add sub array in a JSON file?如何在 JSON 文件中添加子数组?
【发布时间】:2017-03-07 05:34:17
【问题描述】:

我有一个结果 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" ,"名字":"y","姓氏":"y","电话":"2","email":"test@gmail.vp"}, {"id":"31","firstname" :"xxx","姓氏":"xxxx","电话":"12345","email":"test@gmail.com"}, {"id":"33","firstname":"xy" ,"姓氏":"xy","电话":"1","email":"test@gmail.com"}, {"id":"34","firstname":"yyy","lastname" :"yyy","电话":"2","email":"test@gmail.com"}, {"id":"35","firstname":"n","lastname":"n" ,"电话":"1","电子邮件":"test@gmail.com"}, {"id":"36","名字":"q","姓氏":"q","电话" :"1","email":"x@g.com"}, {"id":"37","firstname":"","lastname":"","phone":"","email ":""} ] }

这是我的代码

<?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);
?>

【问题讨论】:

    标签: arrays json


    【解决方案1】:

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

    <?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);
    ?>
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 首先为读取文件编写代码将其存储到变量,然后转换为数组,然后使用数组推送添加新记录再次转换为json并写入您的文件现在找到所有这些步骤有可用的这个堆栈溢出的方法
      【解决方案3】:

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

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

      【讨论】:

      • 似乎@nezhar 打败了我 :)
      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2021-11-20
      • 2021-04-23
      • 2019-04-18
      • 2018-08-25
      • 1970-01-01
      • 2014-07-29
      • 2016-08-21
      相关资源
      最近更新 更多