-1

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

2
  • Assuming the code is doing the right thing, you dont rewrite the file after the changes? Commented Oct 14, 2021 at 14:41
  • No value is still there after execution. Commented Oct 14, 2021 at 14:42

1 Answer 1

1

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)); 
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for your help, can you modify it little i have more values inside that json in concatenate or string, i want to get separate value to call them inside function as single id.
Don't toally understand, can you show a sample of the data and what you want to do with it
{"1":["fileid",time],"2":["fileid",time],"3":["fileid",time]} suppose these are the values, but it returns all $post[1] values as a single string but i have pass single fileid as a string in my function. All File ids are joined as a single string.
Still not sure I understand. I see no function, so maybe if you ADD this next part to your question with an example of what you mean
I'm getting data in this format fileidtimefileidtimefileidtime it is return value like this i want to store single value in var instead of whole data, so how to seprate values using foreach loop after if($dif > 5){ this. i need only fileid or $post[0] value. Hope you understand what i'm trying to say.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.