如何取消设置json对象

Tsc*_*cka 1 php json codeigniter unset

我正在写的是一个临时禁止脚本,适合那些喜欢用小僵尸网络纠缠我的网站的人.

我唯一的问题是如何取消设置json对象.

我有以下代码

/* 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+'); 
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是json编码不会将其编码为数组而是作为对象编码.问题是以下不起作用:

// 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});
Run Code Online (Sandbox Code Playgroud)

如何取消设置json对象?

the*_*fox 6

当您使用json时,Dude json_decode将布尔值true作为第二个参数传递给它.

通过这种方式,您将获得血腥的stdClass.

现在,如果你想删除一个json对象,基本上它是一个字符串,所以只需做一些链接 $var = null;

如果你想取消它的一部分,那么你必须先解码然后编码.

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

unset($my_var["key_of_value_to_delete"]);

$json = json_encode($my_var);
Run Code Online (Sandbox Code Playgroud)

始终将true作为第二个参数传递给json_decode,以强制它对json对象进行递归转换.