如何创建cookie作为数组

时间:2015-11-23 09:27:11

标签: php arrays cookies

我提到这个在cookie中存储数组:Storing and retrieving an array in a PHP cookie

但是,我需要将每个值存储为array.Below是我的脚本:

/*store all values in array starts*/
$search_array=array(
    'category'=>array('cat', $catid),
    'subject'=>array('sub', $subject),
    'location'=>array('loc', $location),
    'rate'=>array('rate', $rate),
    'distance'=>array('dis', $distance)
);

/*store all values in array ends*/

/*cookies starts*/
$s_array= json_encode($search_array);
setcookie('search', $s_array);

/*cookies ends*/

在其他页面中:

<?php
$cookie = $_COOKIE['search'];
$cookie = stripslashes($cookie);
$savedCardArray = json_decode($cookie, true);


var_dump($savedCardArray);
?>

输出结果为:

array (size=5)
  'category' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'cat' (length=3)
          1 => string '5' (length=1)
  'subject' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'sub' (length=3)
          1 => string 'Circuit Training' (length=16)
  'location' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'loc' (length=3)
          1 => string 'gombak' (length=6)
  'rate' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'rate' (length=4)
          1 => int 115
  'distance' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'dis' (length=3)
          1 => string '100' (length=3)

但我想要的是什么(1):

'category' => 
        array (size=1)
          0 => 
            array (size=2)
              0 => string 'cat' (length=3)
              array (size=4)
                 0 => string '5' (length=1)
                 1 => string '2' (length=1)
                 2 => string '4' (length=1)
                 3 => string '10' (length=1)

(2)在48小时内到期

1 个答案:

答案 0 :(得分:1)

$search_array=array(
'category'=>array('cat', array($catid)),
...
);

在48小时内

setcookie("search", $s_array, time()+(3600*48));