Page 1 of 1

Converting String to a $_SESSION result

Posted: Thu Oct 18, 2007 4:27 pm
by jiminald
Hi,

My first time on these forums, so if I have posted it in the wrong place, sorry.

I am trying to convert {SESSION.value1.value2} to $_SESSION[value1][value2]
but the amount of values in the array can change.

Hope I explained that well.. and thanks in advanced! :)

Posted: Thu Oct 18, 2007 6:56 pm
by gregwhitworth
Nope - not well enough for me, but I'm a newb myself. You may want to post your actual PHP for the guru's to scrutinize.

--
Greg

Posted: Thu Oct 18, 2007 9:56 pm
by John Cartwright
I've actually done something extremely similar, so here's a little edited version I can share with you to demonstrate. Hope it helps.

Code: Select all

error_reporting(E_ALL);
session_start();

$_SESSION['foo']['bar']['foobar'] = 'w00t';

preg_match('#{SESSION\.([a-z0-9\.]+)}#i', '{SESSION.foo.bar.foobar}', $matches);

if (count($matches[1])) { 
	$keys = explode('.', $matches[1]);	
	
	// if only one key lets convert it to an array anyways
	if (count($keys) == 0) {
		$keys = array($matches[1][0]);
	}

	// holds the last key that is recursively searched 
	$lastkey = '';
	foreach ($keys as $key) {
		// determine if the key actually exists in the session 
		if (empty($lastkey) && isset($_SESSION[$key])) {
			$lastkey = $_SESSION[$key];
		}
		// determine if the last instance is an array and if we need to continue
		elseif (!empty($lastkey) && is_array($lastkey) && isset($lastkey[$key])) {
			$lastkey = $lastkey[$key];
		}
		// the value does not exist in the session
		else {
                        //reset the value to blank
                        $lastkey = '';
			break;
		}
	}	
	
	echo $lastkey;
}

Posted: Fri Oct 19, 2007 10:40 am
by jiminald
That worked brilliantly!
Had to mod slightly to fit but that saves me from another headache with it tonight!

Thanks :)