Thread: Array mess
View Single Post
Old 12-12-2008, 06:46 PM   #1 (permalink)
Killswitch
The Contributor
 
Join Date: Feb 2007
Posts: 64
Thanks: 9
Killswitch is on a distinguished road
Default Array mess

Arrays are one thing I am trying to strengthen my skills on and have come upon a task that has stumped me for a bit now.

I have a database field called parameters, which contains data that looks like...

this=that,what=where,how=when

I have built a function to seperate the entire string as an array, getting the keys of this, what, and how. It also grabs the keys, that, where, and when.

I have a class to do all this, and class vars to contain the keys, to contain the original array, and to contain the values. What I am trying to do and what is stumping me is how to grab the value of a specific key.

The constructor process and parses the string into an array by calling the parse($string) method. Then I have another method called getValue($key), which is supposed to get a value of the array by the key.

This is all kinda hard to explain, but let me just show you some sloppy code ;)

Code:
 /**@var array of parameters */
 var $_params = null;

 /** @var keys of array */
 var $_keys = null;

 /** @var values of array */
 var $_values = null;
 
 /**
 * Constructor
 * Parses and grabs keys and values from database parameter set
 *
 * @param string Row from table to parse 
 */
 public function __construct($string)
 {
 	 $this->_params = $this->parse($string);
 }
 	
 /**
 * Parses string to seperate values and keys from comma seperated spacers
 *
 * @param string String to parse
 */
 protected function parse($string)
 {		
	// We need to split the string on , to get what=what, then slit that on = to get value
	$split = explode(',', $string);
		
	// Set a few array elements for containers of seperated data
	$sep  = array();
		
	// Cycle through split string, setting values and keys
	$i = 0; // For incrementing
	foreach($split AS $splited)
	{
		$sep[] = explode('=',$splited);
 		$this->_values[] = $sep[$i][1];
 		$this->_keys[] = $sep[$i][0];
 		++$i;
 	}
 }
 	
 /**
 * Gets param value by key
 *
 * @param string key name
 */
 public function getValue($key)
 {
 	 $key = trim($key);
 	 // Check if array key exists
 	 if(array_key_exists($key, $this->_params))
 	 {
              // Ive tried numerous things here, but cant seem to get it...
         }
 	 	 	
 }
Can anyone more familiar with arrays offer a bit of assistance, or point me to what array function I should be checking out? I have downloaded the manual ( that is such a handy thing to have around ) and have been searching through the array functions but haven't seen anything yet to do this easily.
Killswitch is offline  
Reply With Quote