模块

Arr

数组辅助类。

package
BootPHP
category
辅助类
author
Tinsh
copyright
© 2005-2016 Kilofox Studio

该类在 SYSPATH/classes/arr.php 第 13 行声明。

属性

public static string $delimiter

default delimiter for path()

string(1) "."

方法

public static callback( string $str ) (在 Arr 中定义)

Creates a callable function && parameter list from a string representation. Note that this function does not validate the callback string.

// Get the callback function && parameters
list($func, $params) = Arr::callback('Foo::bar(apple,orange)');

// Get the result of the callback
$result = call_user_func_array($func, $params);

参数

  • string $str required - Callback string

返回值

  • array - Function, params

源代码

public static function callback($str)
{
	// Overloaded as parts are found
	$command = $params = NULL;
	// command[param,param]
	if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
	{
		// command
		$command = $match[1];
		if ($match[2] !== '')
		{
			// param,param
			$params = preg_split('/(?<!\\\\),/', $match[2]);
			$params = str_replace('\,', ',', $params);
		}
	}
	else
	{
		// command
		$command = $str;
	}
	if (strpos($command, '::') !== false)
	{
		// Create a static method callable command
		$command = explode('::', $command, 2);
	}
	return array($command, $params);
}

public static extract( array $array , array $keys [, mixed $default = NULL ] ) (在 Arr 中定义)

Retrieves multiple keys from an array. If the key does not exist in the array, the default value will be added instead.

// Get the values "username", "password" from $_POST
$auth = Arr::extract($_POST, array('username', 'password'));

参数

  • array $array required - Array to extract keys from
  • array $keys required - List of key names
  • mixed $default = NULL - Default value

返回值

  • array

源代码

public static function extract($array, array $keys, $default = NULL)
{
	$found = array();
	foreach ($keys as $key)
	{
		$found[$key] = isset($array[$key]) ? $array[$key] : $default;
	}
	return $found;
}

public static flatten( array $array ) (在 Arr 中定义)

Convert a multi-dimensional array into a single-dimensional array.

$array = array('set' => array('one' => 'something'), 'two' => 'other');

// Flatten the array
$array = Arr::flatten($array);

// The array will now be
array('one' => 'something', 'two' => 'other');

The keys of array values will be discarded.

参数

  • array $array required - Array to flatten

返回值

  • array

源代码

public static function flatten($array)
{
	$flat = array();
	foreach ($array as $key => $value)
	{
		if (is_array($value))
		{
			$flat += Arr::flatten($value);
		}
		else
		{
			$flat[$key] = $value;
		}
	}
	return $flat;
}

public static get( array $array , string $key [, mixed $default = NULL ] ) (在 Arr 中定义)

Retrieve a single key from an array. If the key does not exist in the array, the default value will be returned instead.

// Get the value "username" from $_POST, if it exists
$username = Arr::get($_POST, 'username');

// Get the value "sorting" from $_GET, if it exists
$sorting = Arr::get($_GET, 'sorting');

参数

  • array $array required - Array to extract from
  • string $key required - Key name
  • mixed $default = NULL - Default value

返回值

  • mixed

源代码

public static function get($array, $key, $default = NULL)
{
	return isset($array[$key]) ? $array[$key] : $default;
}

public static is_array( mixed $value ) (在 Arr 中定义)

Test if a value is an array with an additional check for array-like objects.

// Returns true
Arr::is_array(array());
Arr::is_array(new ArrayObject);

// Returns false
Arr::is_array(false);
Arr::is_array('not an array!');
Arr::is_array(Database::instance());

参数

  • mixed $value required - Value to check

返回值

  • boolean

源代码

public static function is_array($value)
{
	if (is_array($value))
	{
		// Definitely an array
		return true;
	}
	else
	{
		// Possibly a Traversable object, functionally the same as an array
		return (is_object($value) && $value instanceof Traversable);
	}
}

public static is_assoc( array $array ) (在 Arr 中定义)

Tests if an array is associative || not.

// Returns true
Arr::is_assoc(array('username' => 'john.doe'));

// Returns false
Arr::is_assoc('foo', 'bar');

参数

  • array $array required - Array to check

返回值

  • boolean

源代码

public static function is_assoc(array $array)
{
	// Keys of the array
	$keys = array_keys($array);
	// If the array keys of the keys match the keys, then the array must
	// not be associative (e.g. the keys array looked like {0:0, 1:1...}).
	return array_keys($keys) !== $keys;
}

public static map( mixed $callback , array $array [, array $keys = NULL ] ) (在 Arr 中定义)

Recursive version of array_map, applies the same callback to all elements in an array, including sub-arrays.

// Apply "strip_tags" to every element in the array
$array = Arr::map('strip_tags', $array);

Unlike `array_map`, this method requires a callback && will only map a single array.

参数

  • mixed $callback required - Callback applied to every element in the array
  • array $array required - Array to map
  • array $keys = NULL - Array of keys to apply to

返回值

  • array

源代码

public static function map($callback, $array, $keys = NULL)
{
	foreach ($array as $key => $val)
	{
		if (is_array($val))
		{
			$array[$key] = Arr::map($callback, $array[$key]);
		}
		elseif (!is_array($keys) || in_array($key, $keys))
		{
			if (is_array($callback))
			{
				foreach ($callback as $cb)
				{
					$array[$key] = call_user_func($cb, $array[$key]);
				}
			}
			else
			{
				$array[$key] = call_user_func($callback, $array[$key]);
			}
		}
	}
	return $array;
}

public static merge( array $array1 , array $array2 ) (在 Arr 中定义)

Recursively merge two or more arrays. Values in an associative array overwrite previous values with the same key. Values in an indexed array are appended, but only when they do not already exist in the result.

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 $array1 required - Initial array
  • array $array2 required - ,... array to merge

返回值

  • array

源代码

public static function merge($array1, $array2)
{
	if (Arr::is_assoc($array2))
	{
		foreach ($array2 as $key => $value)
		{
			if (is_array($value)
				AND isset($array1[$key])
				AND is_array($array1[$key])
			)
			{
				$array1[$key] = Arr::merge($array1[$key], $value);
			}
			else
			{
				$array1[$key] = $value;
			}
		}
	}
	else
	{
		foreach ($array2 as $value)
		{
			if (!in_array($value, $array1, TRUE))
			{
				$array1[] = $value;
			}
		}
	}
	if (func_num_args() > 2)
	{
		foreach (array_slice(func_get_args(), 2) as $array2)
		{
			if (Arr::is_assoc($array2))
			{
				foreach ($array2 as $key => $value)
				{
					if (is_array($value)
						AND isset($array1[$key])
						AND is_array($array1[$key])
					)
					{
						$array1[$key] = Arr::merge($array1[$key], $value);
					}
					else
					{
						$array1[$key] = $value;
					}
				}
			}
			else
			{
				foreach ($array2 as $value)
				{
					if (!in_array($value, $array1, TRUE))
					{
						$array1[] = $value;
					}
				}
			}
		}
	}
	return $array1;
}

public static overwrite( array $array1 , array $array2 ) (在 Arr 中定义)

Overwrites an array with values from input arrays. Keys that do not exist in the first array will not be added!

$a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
$a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');

// Overwrite the values of $a1 with $a2
$array = Arr::overwrite($a1, $a2);

// The output of $array will now be:
array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')

参数

  • array $array1 required - Master array
  • array $array2 required - Input arrays that will overwrite existing values

返回值

  • array

源代码

public static function overwrite($array1, $array2)
{
	foreach (array_intersect_key($array2, $array1) as $key => $value)
	{
		$array1[$key] = $value;
	}
	if (func_num_args() > 2)
	{
		foreach (array_slice(func_get_args(), 2) as $array2)
		{
			foreach (array_intersect_key($array2, $array1) as $key => $value)
			{
				$array1[$key] = $value;
			}
		}
	}
	return $array1;
}

public static path( array $array , mixed $path [, mixed $default = NULL , string $delimiter = NULL ] ) (在 Arr 中定义)

Gets a value from an array using a dot separated path.

// Get the value of $array['foo']['bar']
$value = Arr::path($array, 'foo.bar');

Using a wildcard "*" will search intermediate arrays && return an array.

// Get the values of "color" in theme
$colors = Arr::path($array, 'theme.*.color');

// Using an array of keys
$colors = Arr::path($array, array('theme', '*', 'color'));

参数

  • array $array required - Array to search
  • mixed $path required - Key path string (delimiter separated) || array of keys
  • mixed $default = NULL - Default value if the path is not set
  • string $delimiter = NULL - Key path delimiter

返回值

  • mixed

源代码

public static function path($array, $path, $default = NULL, $delimiter = NULL)
{
	if (!Arr::is_array($array))
	{
		// This is not an array!
		return $default;
	}
	if (is_array($path))
	{
		// The path has already been separated into keys
		$keys = $path;
	}
	else
	{
		if (array_key_exists($path, $array))
		{
			// No need to do extra processing
			return $array[$path];
		}
		if ($delimiter === NULL)
		{
			// Use the default delimiter
			$delimiter = Arr::$delimiter;
		}
		// Remove starting delimiters && spaces
		$path = ltrim($path, "{$delimiter} ");
		// Remove ending delimiters, spaces, && wildcards
		$path = rtrim($path, "{$delimiter} *");
		// Split the keys by delimiter
		$keys = explode($delimiter, $path);
	}
	do
	{
		$key = array_shift($keys);
		if (ctype_digit($key))
		{
			// Make the key an integer
			$key = (int) $key;
		}
		if (isset($array[$key]))
		{
			if ($keys)
			{
				if (Arr::is_array($array[$key]))
				{
					// Dig down into the next part of the path
					$array = $array[$key];
				}
				else
				{
					// Unable to dig deeper
					break;
				}
			}
			else
			{
				// Found the path requested
				return $array[$key];
			}
		}
		elseif ($key === '*')
		{
			// Handle wildcards
			$values = array();
			foreach ($array as $arr)
			{
				if ($value = Arr::path($arr, implode('.', $keys)))
				{
					$values[] = $value;
				}
			}
			if ($values)
			{
				// Found the values requested
				return $values;
			}
			else
			{
				// Unable to dig deeper
				break;
			}
		}
		else
		{
			// Unable to dig deeper
			break;
		}
	}
	while ($keys);
	// Unable to find the value requested
	return $default;
}

public static pluck( array $array , string $key ) (在 Arr 中定义)

Retrieves muliple single-key values from a list of arrays.

// Get all of the "id" values from a result
$ids = Arr::pluck($result, 'id');

A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)

参数

  • array $array required - List of arrays to check
  • string $key required - Key to pluck

返回值

  • array

源代码

public static function pluck($array, $key)
{
	$values = array();
	foreach ($array as $row)
	{
		if (isset($row[$key]))
		{
			// Found a value in this row
			$values[] = $row[$key];
		}
	}
	return $values;
}

public static range( [ integer $step = integer 10 , integer $max = integer 100 ] ) (在 Arr 中定义)

Fill an array with a range of numbers.

// Fill an array with values 5, 10, 15, 20
$values = Arr::range(5, 20);

参数

  • integer $step = integer 10 - Stepping
  • integer $max = integer 100 - Ending number

返回值

  • array

源代码

public static function range($step = 10, $max = 100)
{
	if ($step < 1)
		return array();
	$array = array();
	for ($i = $step; $i <= $max; $i += $step)
	{
		$array[$i] = $i;
	}
	return $array;
}

public static set_path( array & $array , string $path , mixed $value [, string $delimiter = NULL ] ) (在 Arr 中定义)

Set a value on an array by path.

参数

  • byref array $array required - Array to update
  • string $path required - Path
  • mixed $value required - Value to set
  • string $delimiter = NULL - Path delimiter

Tags

  • See - Arr::path()

源代码

public static function set_path(& $array, $path, $value, $delimiter = NULL)
{
	if (!$delimiter)
	{
		// Use the default delimiter
		$delimiter = Arr::$delimiter;
	}
	// Split the keys by delimiter
	$keys = explode($delimiter, $path);
	// Set current $array to inner-most array path
	while (count($keys) > 1)
	{
		$key = array_shift($keys);
		if (ctype_digit($key))
		{
			// Make the key an integer
			$key = (int) $key;
		}
		if (!isset($array[$key]))
		{
			$array[$key] = array();
		}
		$array = & $array[$key];
	}
	// Set key on inner-most array
	$array[array_shift($keys)] = $value;
}

public static unshift( array & $array , string $key , mixed $val ) (在 Arr 中定义)

Adds a value to the beginning of an associative array.

// Add an empty value to the start of a select list
Arr::unshift($array, 'none', 'Select a value');

参数

  • byref array $array required - Array to modify
  • string $key required - Array key name
  • mixed $val required - Array value

返回值

  • array

源代码

public static function unshift(array & $array, $key, $val)
{
	$array = array_reverse($array, true);
	$array[$key] = $val;
	$array = array_reverse($array, true);
	return $array;
}