选择语言 :

 Core_Arr::merge

Merges one or more arrays recursively and preserves all keys. Note that this does not work the same as array_merge_recursive!

$john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
$mary = array('name' => 'mary', 'children' => array('jane'));

// John and Mary are married, merge them together
$john = Arr::merge($john, $mary);

// The output of $john will now be:
array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
array Core_Arr::merge( array $a1 , array $a2 )

参数列表

参数 类型 描述 默认值
$a1 array Initial array
$a2 array Array to merge
返回值
  • array
File: ./core/classes/arr.class.php
public static function merge(array $a1, array $a2)
{
	$result = array();
	for ($i = 0, $total = func_num_args(); $i < $total; $i++)
	{
		// Get the next array
		$arr = func_get_arg($i);

		// Is the array associative?
		$assoc = Arr::is_assoc($arr);

		foreach ($arr as $key => $val)
		{
			if (isset($result[$key]))
			{
				if (is_array($val) && is_array($result[$key]))
				{
					if (Arr::is_assoc($val))
					{
						// Associative arrays are merged recursively
						$result[$key] = Arr::merge($result[$key], $val);
					}
					else
					{
						// Find the values that are not already present
						$diff = array_diff($val, $result[$key]);

						// Indexed arrays are merged to prevent duplicates
						$result[$key] = array_merge($result[$key], $diff);
					}
				}
				else
				{
					if ($assoc)
					{
						// Associative values are replaced
						$result[$key] = $val;
					}
					elseif (!in_array($val, $result, true))
					{
						// Indexed values are added only if they do not yet exist
						$result[] = $val;
					}
				}
			}
			else
			{
				// New values are added
				$result[$key] = $val;
			}
		}
	}

	return $result;
}