NYCPHP Meetup

NYPHP.org

[nycphp-talk] Overriding Array's

Andy Dirnberger dirn at dirnonline.com
Thu May 3 23:04:03 EDT 2007


Like really sad.

Sent via BlackBerry from Cingular Wireless  

-----Original Message-----
From: "Joseph Crawford" <codebowl at gmail.com>
Date: Thu, 3 May 2007 22:57:12 
To:"NYPHP Talk" <talk at lists.nyphp.org>
Subject: Re: [nycphp-talk] Overriding Array's

Rob,

Thanks for your code example however having them as class properties
will not work.  The main reason is that the default array is created
by reading a YAML file.  The array is populated by reading a section
of a flat file and then it reads a section specific to the current
page (if any) and overrides the defaults.  Here is the code I have
used to accomplish this.

Thanks to every who responded.

	// parse through an array, $a is the original array and
	// $b is the new array to merge into it
	function override($a, $b)
	{
		// an array that will hold the new, properly
		// merged version of the two arrays
		$new = array();

		// if we've encountered numbered keys, this
		// will be true
		$numbers = FALSE;

		// if $a is bigger than $b, lots of code repetition
		// beyond this point.. ugh.
		if(count($a) >= count($b))
		{
			// override the arrays if necessary
			foreach($a as $key => $val)
			{
				// if we've found a number, stop the loop
				if(is_numeric($key)) // dunno why ctype_digit didn't work...
				{
					$numbers = TRUE;
					break;
				}

				// otherwise, override the key with a $b value
				// if it exists.
				else
				$new[$key] = isset($b[$key]) ? $b[$key] : $a[$key];
			}
		}

		// otherwise..
		else
		{

			// override the arrays if necessary
			foreach($b as $key => $val)
			{
				if(is_numeric($key))
				{
					$numbers = TRUE;
					break;
				}

				// otherwise, override the key with an $a value
				// if it exists.
				else
				$new[$key] = isset($a[$key]) ? $a[$key] : $b[$key];
			}
		}

		// merge the arrays if they are numbered keys

		if($numbers)
		$new = array_merge($a, $b);

		// loop through the new array and check for sub-arrays
		foreach($new as $key => $val)
		{
			// recursively go through
			if(is_array($new[$key]) && !$numbers)
			$new[$key] = $this->override((isset($a[$key]) ? $a[$key] :
array()), (isset($b[$key]) ? $b[$key] : array()));
		}



		// return the new, merged array
		return $new;
	}

-- 
Joseph Crawford Jr.
Zend Certified Engineer
Codebowl Solutions, Inc.
http://www.codebowl.com/
Blog: http://www.josephcrawford.com/
1-802-671-2021
codebowl at gmail.com
_______________________________________________
New York PHP Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk

NYPHPCon 2006 Presentations Online
http://www.nyphpcon.com

Show Your Participation in New York PHP
http://www.nyphp.org/show_participation.php



More information about the talk mailing list