1

What I am writing is a temporarely banning script for people who like to pester my site with small botnets.

The only problem I am having is how to unset a json object.

I have the following code

/* JSON blocking script written by Michael Dibbets
 * Copyright 2012 by Michael Dibbets
 * http://www.facebook.com/michael.dibbets - mdibbets[at]outlook.com
 * Licenced under the MIT license http://opensource.org/licenses/MIT
 */
    // Turn on error reporting
    ini_set("display_errors", 1);
    error_reporting(E_ALL);  
    // Create our codeigniter filepath
    $filepath = FCPATH.'pagemodules/blocked.json';
    // Load file helper to be able to be lazy
    $this->load->helper('file');
    // Read the json file
    $data = read_file($filepath,'c+');
    // Have we succeeded? Then continue, otherwise fail graciously
    if($data !== false)
        {
            // Let's make it readable
        $json = json_decode($data);
            // Display it for debug purposes
        echo $data;
            // Iterate through every object, get the key to be able to unset it
        foreach($json as $key => $obj)
            {
                    // Dump the object for debug purposes
            var_dump($obj);
            echo "<P>";
                    // Has it's life time expired?
            if((int)$obj->{'endtime'} < strtotime("+2 hours 2 minutes"));
                {
                            // remove the object from the array
                unset($json[$key]);
                }
            }
            // Remove the file so we can overwrite it properly
        unlink($filepath); 
        }
    // Add some values to our array
    $json[] = array('ip' => $_SERVER['REMOTE_ADDR'],'endtime' => strtotime('+2 hours'));
    // Encode it
    $data = json_encode($json);
    // Write it to file
    write_file($filepath,$data,'c+'); 

The problem I am having is that json encode doesn't encode it as array but as an object. The problem is that the following doesn't work:

// This gives the error Fatal error: Cannot use object of type stdClass as array in /public_html/ocs_application/controllers/quick.php on line 37
unset($json[$key]);
// This doesn't report anything, and does nothing
unset($json->{$key});

How do I unset the json object?

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • Duplicate ? http://stackoverflow.com/questions/7044967/delete-from-json-using-php .... http://stackoverflow.com/questions/2901562/json-search-and-remove-in-php – TigerTiger Aug 03 '12 at 07:31
  • That is what I tried. But it's encoded as an object. If you follow the code you can see that I start everything as arrays, but json_encode decides to make it into an object string instead of array string. – Tschallacka Aug 03 '12 at 07:34

2 Answers2

6

Dude when you use json json_decode pass it a boolean true as a second parameter.

this way you will get ride of the bloody stdClass.

Now if you want to delete a json object basically it's a string so just do something link $var = null;

if you want to unset part of it then you have to decode it first then encode it.

$my_var = json_decode($json, true); // convert it to an array.

unset($my_var["key_of_value_to_delete"]);

$json = json_encode($my_var);

Always pass to true as a second param to json_decode in order to force it to do recursive conversion of the json object.

thedethfox
  • 1,651
  • 2
  • 20
  • 38
  • 1
    Dude, you're a godsent! Thank you very much. This has made my life a lot easier! Should have noticed it before, but got stuck in a rut. Thank you very much! You have tought me a valuable lesson about json decode. – Tschallacka Aug 03 '12 at 07:46
  • why unset change json array of object ? my json is : [{"proId":"3","sizeId":"1","number":1},{"proId":"1","sizeId":"","number":"10"},{"proId":"3","sizeId":"1","number":1}] but after unset like this : {"0":{"proId":"3","colorId":"1","sizeId":"1","number":1},"2":{"proId":"3","colorId":"2","sizeId":"1","number":1}} – farzad Oct 20 '17 at 18:19
  • @farzad i have the same problem, encoding is not work properly, it add some extra numbers on json. Array ( [0] => Array ( [platform] => x [link] => x [videono] => x ) [1] => Array ( [platform] => eders1 [link] => 313389 [videono] => 0 ) ) This array return to this json {"0":{"platform":"x","link":"x","videono":"x"},"1":{"platform":"eders1","link":"313389","videono":"0"}} – matasoy Oct 23 '20 at 07:26
3

Just to make clear that unset() works with both JSON objects and arrays:

$json_str = '{"foo": 1, "bar": 2, "baz": 3}';
$json_obj = json_decode($json_str);
$json_arr = json_decode($json_str, true);

var_dump($json_obj); // object(stdClass)#1 (3) { ["foo"]=> int(1) ["bar"]=> int(2) ["baz"]=> int(3) }
var_dump($json_arr); // array(3) { ["foo"]=> int(1) ["bar"]=> int(2) ["baz"]=> int(3) }    

unset($json_obj->baz);
unset($json_arr['baz']);

var_dump($json_obj); // object(stdClass)#1 (2) { ["foo"]=> int(1) ["bar"]=> int(2) }
var_dump($json_arr); // array(2) { ["foo"]=> int(1) ["bar"]=> int(2) }

$key = 'bar';
unset($json_obj->$key);
unset($json_arr[$key]);

var_dump($json_obj); // object(stdClass)#1 (1) { ["foo"]=> int(1) }
var_dump($json_arr); // array(1) { ["foo"]=> int(1) }
Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
  • Okay, and what about when you don't know the object name you want to unset? Like in my example if you don't use the true variable in the json decode? – Tschallacka Aug 03 '12 at 08:09