Bloody mess of a function
Posted: Sun Mar 08, 2009 3:41 pm
I just can't wrap my head around this one. I'm using array cookies (ie: $_COOKIE['site']['dir']['SID']) and I couldn't find anything to handle them so I wrote this function:
Result:
The function works, but I know that it can be simplified, A LOT. I'd like to use preg_match_all to extract each array level ie: $parts[0]="site[dir][SID]" -> $array[0]="site", $array[1]="dir", $array[2]="SID". I was trying something like:
But alas, no dice.
For the life of me I can't figure out how to loop through the flat array of $keys and convert it to a stacked array like the results above. Any help is appreciated.
Code: Select all
// Cookie set on prior page... notice cookie naming convention
setcookie('site[dir][SID]', $session_id...);
function stackCookies()
{
if ( isset($_SERVER['HTTP_COOKIE']) )
{
//print $_SERVER['HTTP_COOKIE'];// results below
//site[dir][SID]=855rq5m9Re1I7bJ1L5b2d5dD7Z4rs8A8; site[dir][USR]=username; site=d0ba6a76ddb885eda8478da46c66ee1eArray
// Split $_SERVER['HTTP_COOKIE'] into individual cookies
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach ( $cookies as $cookie )
{
// Split to $keys = $value pairs
$parts = explode('=', trim($cookie));
// Split string into array -> change to preg_match_all()
$tmp_keys = str_replace(array('][','[',']'), array('_','_',''), $parts[0]);
$keys = explode('_', $tmp_keys);
$value = $parts[1];
// Stack 2d array $keys as 3d array -> change to loop
if ( count($keys) == 4 )
{
$cookie_array[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = $value;
}
elseif ( count($keys) == 3 )
{
$cookie_array[$keys[0]][$keys[1]][$keys[2]] = $value;
}
elseif ( count($keys) == 2 )
{
$cookie_array[$keys[0]][$keys[1]] = $value;
}
}
return $cookie_array;
}
return NULL;
}
print_r(stackCookies());
Code: Select all
Array
(
[site] => Array
(
[dir] => Array
(
[SID] => 855rq5m9Re1I7bJ1L5b2d5dD7Z4rs8A8
[USR] => username
)
)
)
Code: Select all
preg_match_all("/\[[\w+]\]/", $parts[0], $matches, PREG_SET_ORDER);
For the life of me I can't figure out how to loop through the flat array of $keys and convert it to a stacked array like the results above. Any help is appreciated.