【问题标题】:How to append in JSON file at specific position using PHP如何使用 PHP 在特定位置附加 JSON 文件
【发布时间】:2020-09-05 09:51:51
【问题描述】:

JSON 文件以前的数据,其中只有一条记录

JSON 数据描述了一个数组,该数组的每个元素都是一个对象。

[
   {
      id       : '1'
      name     : 'dfg ggg',
      age      : '17',
      address  : 'somewhere',
      dob      : '10/05/2002'
   }
]

我只想在顶部添加具有相同对象的新数组

然后我想在顶部添加这样的数据...

在这里,我在顶部添加了另外 2 个记录作为数组,这是前 2 个数组。

[
   {
      id       : '3'
      name     : 'sssd dsyz',
      age      : '10',
      address  : 'somewhere',
      dob      : '10/05/2010'
   },
   {
      id       : '2'
      name     : 'Abc Xyz',
      age      : '15',
      address  : 'somewhere',
      dob      : '10/05/2005'
   },
   {
      id       : '1'
      name     : 'dfg ggg',
      age      : '17',
      address  : 'somewhere',
      dob      : '10/05/2002'
   }
]

【问题讨论】:

标签: php json file object append


【解决方案1】:

我在 php 中有这段代码,用于在最后一个位置附加数据数组。但我想在 0 位置追加数据数组。

<?php
$current_data = file_get_contents('myfile.json');  
$array_data = json_decode($current_data, true);  
$extra = array(
                'id'       =>   $_POST['id'],
                'name'     =>   $_POST['name'],
                'age'      =>   $_POST['age'],
                'address'  =>   $_POST['address'],
                'dob'      =>   $_POST['dob'],
              );  
                $array_data[] = $extra;  
                $final_data = json_encode($array_data);  
                if(file_put_contents('myfile.json', $final_data))  
                {  
                     $message = "<label class='text-success'>File Appended Success fully</p>";  
                }
?>

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 2022-11-15
    • 1970-01-01
    • 2018-04-12
    • 2011-06-18
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多