1

这是一个奇怪的问题,所以请耐心等待。问你们真的是我最后的手段。

需要明确的是,我使用的是 Kohana 3.3,尽管我什至不确定这与问题有关。

我正在使用 cookie 来跟踪网站上的已读项目。cookie 包含一个 json_encoded 数组。添加到该数组不是问题,每次读取新项目时都会添加对象。数组中的一个项目包含一个带有last_view_date和 a的对象view_count为了更新视图计数,我需要检查该项目是否已被读取array_key_exists,然后添加到视图计数中。这是我设置cookie的方式:

// Get the array from the cookie.
$cookie_value = Cookie::get_array('read_items');

// Update the view_count based on whether the id exists as a key.
$view_count = (array_key_exists($item->id, $cookie_value)) ? 
                $cookie_value[$item->id]['view_count'] + 1 : 1;

// Create the item to be added to the cookie.
$cookie_item = array(
    'last_view_date' => time(),
    'view_count' => $view_count
);

// Push $cookie_item to the cookie array.
Cookie::push('read_items', $item->id, $cookie_item);

我在Kohana 的 Cookie 类中添加了两个方法,Cookie::pushCookie::get_array,在上面的代码中使用:

class Cookie extends Kohana_Cookie {

    public static function push($cookie_name, $key, $value)
    {
        $cookie_value = parent::get($cookie_name);

        // Add an empty array to the cookie if it doesn't exist.
        if(!$cookie_value)
        {
            parent::set($cookie_name, json_encode(array()));
        }
        else
        {
            $cookie_value = (array)json_decode($cookie_value);

            // If $value isn't set, append without key.
            if(isset($value))
            {
                $cookie_value[$key] = $value;
            }
            else
            {
                $cookie_value[] = $key;
            }
            Cookie::set($cookie_name, json_encode($cookie_value));
        }
    }

    public static function get_array($cookie_name)
    {
        return (array)json_decode(parent::get($cookie_name));
    }
}

现在,这是我的问题。运行var_dumpon$cookie_value输出以下内容:

array(1) {
  ["37"]=>
  object(stdClass)#43 (2) {
    ["last_view_date"]=>
    int(1359563215)
    ["view_count"]=>
    int(1)
  }
}

但是当我尝试访问时$cookie_value[37],我不能:

var_dump(array_key_exists(37, $cookie_value));
// Outputs bool(false);

var_dump(is_array($cookie_value));
// Outputs bool(true);

var_dump(count($cookie_value));
// Outputs int(1);

var_dump(array_keys($cookie_value));
// Outputs:
// array(1) {
//   [0]=>
//   string(2) "37"
// }

添加调试代码:

var_dump(isset($cookie_value["37"]));
// Outputs bool(false).

var_dump(isset($cookie_value[37]));
// Outputs bool(false).

var_dump(isset($cookie_value[(string)37]));
// Outputs bool(false).

我希望它足够清楚。

4

2 回答 2

1

使用以下方式访问值:-

$cookie_value["37"]

“37”(键)是字符串格式。您将其指定为整数($cookie_value[37])

于 2013-01-30T17:13:31.120 回答
1

看看json_decode。目前,您正在将结果转换为数组。如果您将 true 作为第二个参数传递给 json_decode,您将得到一个数组而不是 stdObject。

该问题也可能与您检查 int 与字符串键有关。您可以通过在服务器上运行此代码进行测试:

<?php  

$one = array("37" => "test");
$two = array(37 => "test");

var_dump(array_key_exists(37,$one)); // true or false?
var_dump(array_key_exists(37,$two)); // true

?>
于 2013-01-30T17:22:36.513 回答