How can i delete value from json encode array using php. here is my json format.
{"1":["fileid",time],"2":["fileid",time],"3":["fileid",time]}
And here is my php code. but nothing is delete. i want to remove whole array value ex
"3":["fileid",time]
when function execute.
<?php
$filename = "test.json";
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
foreach($decode as $post){
$dif = time() - $post[1];
if($dif > 5){
foreach ((array)$post[0] as $val => $v) {
echo $id = $v.'<br>';
}
unset($decode[1]);
}
?>
Thanks
CodePudding user response:
You need an index, rather than always unsetting occurance 1
. So change your foreach
as below and use that index $i
on the original array
You can also simplify the file read to file_get_contents()
$buf = file_get_contents("test.json");
$array = json_decode($buf,true);
foreach($array as $i => $post){
$dif = time() - $post[1];
if($dif > 5){
unset($array[$i]);
}
}
file_put_contents("test2.json",json_encode($array));