All pastes #467939 Raw Edit

k4st

public text v1 · immutable
·published 2007-05-02 20:18 UTC
rendered paste body
// parse through an array, $a is the original array and
// $b is the new array to merge into it
function parse_array($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((string)(int)$key == $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((string)(int)$key == $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]) && !is_numeric($key))
			$new[$key] = parse_array((isset($a[$key]) ? $a[$key] : array()), (isset($b[$key]) ? $b[$key] : array()));
	}
		
	// return the new, merged array
	return $new;
}