112233
112233

Reputation: 2466

How to create cookie as array

I referred to this to store array in cookie: Storing and retrieving an array in a PHP cookie

However, I need each value stored as array.Below is my script:

/*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*/

In other page:

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


var_dump($savedCardArray);
?>

The output is:

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)

But what I want (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) to expire within 48 hours

Upvotes: 1

Views: 292

Answers (1)

Monk Ren
Monk Ren

Reputation: 57

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

in 48 hours

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

Upvotes: 1

Related Questions