How to unset data from json file

时间:2017-07-10 15:29:54

标签: javascript php arrays json

how do i delete my data in json file, heres my json file data, i want to clear the data of my json file.

 {"name":null,"timestart":"00:00","timeend":"00:00","day":null},
 {"name":"henrix","timestart":"7:00","timeend":"7:30","day":"tuesday"}]

i tried this code but its not delete the data, its saving another data but its null

<?php 

$file = 'timetable.json';
$json_file  = file_get_contents($file);
$file_content = json_decode($json_file);

foreach ($file_content as $key => $value) {

$name = $file_content[$key]->name;
$timestart = date("H:i", strtotime($file_content[$key]->timestart));
$timeend = date("H:i", strtotime($file_content[$key]->timeend));
$day = $file_content[$key]->day;
$reservations[] = array(
  "name" => $name,
  'timestart'=> $timestart,
  'timeend'=> $timeend,
  'day'=> $day
  );
 }

  $reservations[] = array(
  "name" => null,
  'timestart'=> null,
  'timeend'=> null,
  'day'=> null
  );

file_put_contents($file, json_encode($reservations));

$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'henriks.php';
header("Location: http://$host$uri/$extra");
exit();

?>

3 个答案:

答案 0 :(得分:0)

你不能只输出一个空的Json字符串吗?

file_put_contents('yourFile.json', json_encode([] /* empty array */))

答案 1 :(得分:0)

使用delete:delete $reservations[].name

答案 2 :(得分:0)

这是有道理的,因为你是json_encoding()一个包含数据($reservations)的数组,虽然是空值。

假设你想要一个空数组,那就应该这样做。

file_put_contents('timetable.json', "[]");