2017-07-10 36 views
0

如何在json文件中刪除我的數據,繼承人我的json文件數據,我想清除我的json文件的數據。如何從json文件中取消設置

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

我想這代碼,但它不會刪除數據,其保存的另一個數據,但其空

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

?> 
+0

'code' $ value){ \t unset($ file_content [$ key]); } $保留[] =陣列( 「名稱」=>空, 'timestart'=>空, 'timeend'=>空, '天'=>空 ); 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(); ?> –

回答

0

你不能只輸出一個空的JSON字符串中呢?

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

現在工作。抱歉。 –

+0

<?php $ file ='timetable.json'; $ json_file = file_get_contents($ file); $ file_content = json_decode($ json_file); foreach($ file_content as $ key => $ value){ \t unset($ file_content [$ key]); } $保留[] =陣列( 「名稱」=>空, 'timestart'=>空, 'timeend'=>空, '天'=>空 ); 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(); ?> –

0

使用刪除:delete $reservations[].name

+0

其工作抱歉,我剛剛刪除了一些代碼並添加了一些。 –

0

那麼它是有道理的,因爲你json_encoding(),其中包含數據($reservations)的陣列,儘管空值。

假設你想要一個空數組,這應該做到這一點。 ?

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

其工作抱歉,我剛剛刪除了一些代碼並添加了一些。 –

相關問題