これは奇妙なものなので、我慢してください。皆さんに本当に尋ねるのは私の最後の手段です。
明確にするために、私は Kohana 3.3 を使用していますが、それが問題に関連しているのかどうかさえわかりません。
Cookie を使用して、Web サイトの既読アイテムを追跡しています。Cookie には json_encoded 配列が含まれています。その配列への追加は問題ではありません。新しいアイテムが読み込まれるたびにオブジェクトが追加されます。last_view_date
配列内のアイテムには、とを持つオブジェクトが含まれていますview_count
。ビュー カウントを更新するために、アイテムが既に使用されているかどうかを確認array_key_exists
し、ビュー カウントに追加する必要があります。クッキーを設定する方法は次のとおりです。
// 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::push
に2 つのメソッドを追加しました。Cookie::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_dump
on を実行すると$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).
十分に明確であることを願っています。