php json file operations

  • First, there is a json file for storage.json, reads as follows:

Here Insert Picture Description

1. Read json file

Code:

<?php
// 从文件中读取数据到PHP变量
 $constans =file_get_contents('storage.json');
 // 把JSON字符串转成PHP数组
 $data=json_decode($constans,true);
 //用var_dump() 显示出来看看
 var_dump($data);
 echo '<br><br>';
 //foreach读取所有
  foreach ($data as $item){
  	echo $item['id'];
  	echo $item['name'];
  }
    echo '<br><br>';
 //读取具体内容,读取第一个name
   echo  $data[0]['name'];
?>

effect:
Here Insert Picture Description

2. additional content json file

<?php
// 把JSON字符串转成PHP数组
$origin = json_decode(file_get_contents('storage.json'), true);
//在数组里添加内容
  $origin[] = array(
    'id' => '04',
    'name' => 'four',
   
  );
// 再把PHP数组转为JSON字符串
  $json = json_encode($origin);
 // 写入文件
   file_put_contents('storage.json', $json);
?>

effect:
Here Insert Picture Description

3. Create a json file

<?php
//生成一个PHP数组
$new_js = array();
//在php数组写入数据
$new_js[0] = array('1','我是新的1');
$new_js[1] = array('2','我是新的2');
// 把PHP数组转成JSON字符串
$json_string = json_encode($new_js);
// 写入文件,有同名的 JSON 文件则覆盖,没有则创建。
file_put_contents('test.json', $json_string);
?>

effect:
Here Insert Picture Description

4. Delete the contents of json

<?php
// 假设要删除id为01的数据
$id ='01';
// 找到要删除的数据
$data = json_decode(file_get_contents('storage.json'), true);
   foreach ($data as $item) {
   // 不是我们要的之间找下一条
   if ($item['id'] !== $id) continue;
   // $item => 我们要删除的那一条数据
   // 从原有数据中移除
   $index = array_search($item, $data);
   //删除
  array_splice($data, $index, 1);
  // 把PHP数组转成JSON字符串
  $json = json_encode($data);
  file_put_contents('storage.json', $json);

}
?>

effect:
Here Insert Picture Description

Published 16 original articles · won praise 2 · Views 198

Guess you like

Origin blog.csdn.net/weixin_43482965/article/details/104468461
Recommended