ArrayHelper.php 9.15 KB
Newer Older
Qiang Xue committed
1 2 3 4 5
<?php
/**
 * ArrayHelper class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9 10 11
 * @license http://www.yiiframework.com/license/
 */

namespace yii\util;

Qiang Xue committed
12 13
use yii\base\InvalidCallException;

Qiang Xue committed
14
/**
15 16
 * ArrayHelper provides additional array functionality you can use in your
 * application.
Qiang Xue committed
17 18 19 20
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
21
class ArrayHelper
Qiang Xue committed
22 23
{
	/**
Qiang Xue committed
24
	 * Merges two or more arrays into one recursively.
Qiang Xue committed
25 26 27 28 29 30 31
	 * If each array has an element with the same string key value, the latter
	 * will overwrite the former (different from array_merge_recursive).
	 * Recursive merging will be conducted if both arrays have an element of array
	 * type and are having the same key.
	 * For integer-keyed elements, the elements from the latter array will
	 * be appended to the former array.
	 * @param array $a array to be merged to
Qiang Xue committed
32 33
	 * @param array $b array to be merged from. You can specify additional
	 * arrays via third argument, fourth argument etc.
Qiang Xue committed
34 35 36 37
	 * @return array the merged array (the original arrays are not changed.)
	 */
	public static function merge($a, $b)
	{
Qiang Xue committed
38 39 40 41 42 43 44 45 46 47 48 49
		$args = func_get_args();
		$res = array_shift($args);
		while ($args !== array()) {
			$next = array_shift($args);
			foreach ($next as $k => $v) {
				if (is_integer($k)) {
					isset($res[$k]) ? $res[] = $v : $res[$k] = $v;
				} elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
					$res[$k] = self::merge($res[$k], $v);
				} else {
					$res[$k] = $v;
				}
Qiang Xue committed
50 51
			}
		}
Qiang Xue committed
52
		return $res;
Qiang Xue committed
53 54 55
	}

	/**
Qiang Xue committed
56
	 * Retrieves the value of an array element or object property with the given key or property name.
Qiang Xue committed
57
	 * If the key does not exist in the array, the default value will be returned instead.
Qiang Xue committed
58 59
	 *
	 * Below are some usage examples,
Qiang Xue committed
60 61
	 *
	 * ~~~
Qiang Xue committed
62
	 * // working with array
Qiang Xue committed
63
	 * $username = \yii\util\ArrayHelper::getValue($_POST, 'username');
Qiang Xue committed
64
	 * // working with object
Qiang Xue committed
65
	 * $username = \yii\util\ArrayHelper::getValue($user, 'username');
Qiang Xue committed
66
	 * // working with anonymous function
Qiang Xue committed
67
	 * $fullName = \yii\util\ArrayHelper::getValue($user, function($user, $defaultValue) {
Qiang Xue committed
68 69
	 *     return $user->firstName . ' ' . $user->lastName;
	 * });
Qiang Xue committed
70 71
	 * ~~~
	 *
Qiang Xue committed
72 73 74 75
	 * @param array|object $array array or object to extract value from
	 * @param string|\Closure $key key name of the array element, or property name of the object,
	 * or an anonymous function returning the value. The anonymous function signature should be:
	 * `function($array, $defaultValue)`.
Qiang Xue committed
76
	 * @param mixed $default the default value to be returned if the specified key does not exist
Qiang Xue committed
77
	 * @return mixed the value of the
Qiang Xue committed
78
	 */
Qiang Xue committed
79
	public static function getValue($array, $key, $default = null)
Qiang Xue committed
80
	{
Qiang Xue committed
81
		if ($key instanceof \Closure) {
Qiang Xue committed
82
			return $key($array, $default);
Qiang Xue committed
83 84 85 86 87
		} elseif (is_array($array)) {
			return isset($array[$key]) || array_key_exists($key, $array) ? $array[$key] : $default;
		} else {
			return $array->$key;
		}
Qiang Xue committed
88
	}
Qiang Xue committed
89 90

	/**
91 92 93 94 95 96 97 98
	 * Indexes an array according to a specified key.
	 * The input array should be multidimensional or an array of objects.
	 *
	 * The key can be a key name of the sub-array, a property name of object, or an anonymous
	 * function which returns the key value given an array element.
	 *
	 * If a key value is null, the corresponding array element will be discarded and not put in the result.
	 *
Qiang Xue committed
99 100 101 102 103 104 105 106 107 108 109
	 * For example,
	 *
	 * ~~~
	 * $array = array(
	 *     array('id' => '123', 'data' => 'abc'),
	 *     array('id' => '345', 'data' => 'def'),
	 * );
	 * $result = ArrayHelper::index($array, 'id');
	 * // the result is:
	 * // array(
	 * //     '123' => array('id' => '123', 'data' => 'abc'),
110
	 * //     '345' => array('id' => '345', 'data' => 'def'),
Qiang Xue committed
111 112 113 114 115 116
	 * // )
	 *
	 * // using anonymous function
	 * $result = ArrayHelper::index($array, function(element) {
	 *     return $element['id'];
	 * });
117
	 * ~~~
Qiang Xue committed
118
	 *
119 120
	 * @param array $array the array that needs to be indexed
	 * @param string|\Closure $key the column name or anonymous function whose result will be used to index the array
Qiang Xue committed
121
	 * @return array the indexed array
Qiang Xue committed
122 123 124 125
	 */
	public static function index($array, $key)
	{
		$result = array();
Qiang Xue committed
126
		foreach ($array as $element) {
Qiang Xue committed
127
			$value = static::getValue($element, $key);
Qiang Xue committed
128
			$result[$value] = $element;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
		}
		return $result;
	}

	/**
	 * Returns the values of a specified column in an array.
	 * The input array should be multidimensional or an array of objects.
	 *
	 * For example,
	 *
	 * ~~~
	 * $array = array(
	 *     array('id' => '123', 'data' => 'abc'),
	 *     array('id' => '345', 'data' => 'def'),
	 * );
Qiang Xue committed
144
	 * $result = ArrayHelper::getColumn($array, 'id');
145 146 147
	 * // the result is: array( '123', '345')
	 *
	 * // using anonymous function
Qiang Xue committed
148
	 * $result = ArrayHelper::getColumn($array, function(element) {
149 150 151 152 153
	 *     return $element['id'];
	 * });
	 * ~~~
	 *
	 * @param array $array
Qiang Xue committed
154 155 156
	 * @param string|\Closure $name
	 * @param boolean $keepKeys whether to maintain the array keys. If false, the resulting array
	 * will be re-indexed with integers.
157 158
	 * @return array the list of column values
	 */
Qiang Xue committed
159
	public static function getColumn($array, $name, $keepKeys = true)
160 161
	{
		$result = array();
Qiang Xue committed
162 163 164 165 166 167 168 169
		if ($keepKeys) {
			foreach ($array as $k => $element) {
				$result[$k] = static::getValue($element, $name);
			}
		} else {
			foreach ($array as $element) {
				$result[] = static::getValue($element, $name);
			}
Qiang Xue committed
170
		}
Qiang Xue committed
171

Qiang Xue committed
172 173
		return $result;
	}
174 175 176 177

	/**
	 * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
	 * The `$from` and `$to` parameters specify the key names or property names to set up the map.
Qiang Xue committed
178
	 * Optionally, one can further group the map according to a grouping field `$group`.
179 180 181 182 183
	 *
	 * For example,
	 *
	 * ~~~
	 * $array = array(
Qiang Xue committed
184 185 186
	 *     array('id' => '123', 'name' => 'aaa', 'class' => 'x'),
	 *     array('id' => '124', 'name' => 'bbb', 'class' => 'x'),
	 *     array('id' => '345', 'name' => 'ccc', 'class' => 'y'),
187
	 * );
Qiang Xue committed
188 189 190 191 192 193 194 195 196 197
	 *
	 * $result = ArrayHelper::map($array, 'id', 'name');
	 * // the result is:
	 * // array(
	 * //     '123' => 'aaa',
	 * //     '124' => 'bbb',
	 * //     '345' => 'ccc',
	 * // )
	 *
	 * $result = ArrayHelper::map($array, 'id', 'name', 'class');
198 199
	 * // the result is:
	 * // array(
Qiang Xue committed
200 201 202 203 204 205 206
	 * //     'x' => array(
	 * //         '123' => 'aaa',
	 * //         '124' => 'bbb',
	 * //     ),
	 * //     'y' => array(
	 * //         '345' => 'ccc',
	 * //     ),
207 208 209
	 * // )
	 * ~~~
	 *
Qiang Xue committed
210
	 * @param array $array
Qiang Xue committed
211 212 213
	 * @param string|\Closure $from
	 * @param string|\Closure $to
	 * @param string|\Closure $group
214 215
	 * @return array
	 */
Qiang Xue committed
216
	public static function map($array, $from, $to, $group = null)
217 218 219
	{
		$result = array();
		foreach ($array as $element) {
Qiang Xue committed
220 221
			$key = static::getValue($element, $from);
			$value = static::getValue($element, $to);
Qiang Xue committed
222
			if ($group !== null) {
Qiang Xue committed
223
				$result[static::getValue($element, $group)][$key] = $value;
Qiang Xue committed
224 225
			} else {
				$result[$key] = $value;
226 227 228 229
			}
		}
		return $result;
	}
230 231

	/**
Qiang Xue committed
232 233 234 235 236 237 238 239 240 241 242
	 * Sorts an array of objects or arrays (with the same structure) by one or several keys.
	 * @param array $array the array to be sorted. The array will be modified after calling this method.
	 * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
	 * elements, a property name of the objects, or an anonymous function returning the values for comparison
	 * purpose. The anonymous function signature should be: `function($item)`.
	 * To sort by multiple keys, provide an array of keys here.
	 * @param boolean|array $ascending whether to sort in ascending or descending order. When
	 * sorting by multiple keys with different ascending orders, use an array of ascending flags.
	 * @param integer|array $sortFlag the PHP sort flag. Valid values include:
	 * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, and `SORT_STRING | SORT_FLAG_CASE`. The last
	 * value is for sorting strings in case-insensitive manner. Please refer to
Qiang Xue committed
243
	 * See [PHP manual](http://php.net/manual/en/function.sort.php) for more details.
Qiang Xue committed
244
	 * When sorting by multiple keys with different sort flags, use an array of sort flags.
Qiang Xue committed
245
	 * @throws InvalidCallException if the $ascending or $sortFlag parameters do not have
Qiang Xue committed
246
	 * correct number of elements as that of $key.
247
	 */
248
	public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR)
249
	{
Qiang Xue committed
250 251 252
		$keys = is_array($key) ? $key : array($key);
		if (empty($keys) || empty($array)) {
			return;
253
		}
Qiang Xue committed
254 255 256 257
		$n = count($keys);
		if (is_scalar($ascending)) {
			$ascending = array_fill(0, $n, $ascending);
		} elseif (count($ascending) !== $n) {
Qiang Xue committed
258
			throw new InvalidCallException('The length of $ascending parameter must be the same as that of $keys.');
259
		}
Qiang Xue committed
260 261 262
		if (is_scalar($sortFlag)) {
			$sortFlag = array_fill(0, $n, $sortFlag);
		} elseif (count($sortFlag) !== $n) {
Qiang Xue committed
263
			throw new InvalidCallException('The length of $ascending parameter must be the same as that of $keys.');
Qiang Xue committed
264
		}
Qiang Xue committed
265 266 267 268 269 270 271 272 273 274 275 276 277
		$args = array();
		foreach ($keys as $i => $key) {
			$flag = $sortFlag[$i];
			if ($flag == (SORT_STRING | SORT_FLAG_CASE)) {
				$flag = SORT_STRING;
				$column = array();
				foreach (static::getColumn($array, $key) as $k => $value) {
					$column[$k] = strtolower($value);
				}
				$args[] = $column;
			} else {
				$args[] = static::getColumn($array, $key);
			}
278
			$args[] = $ascending[$i] ? SORT_ASC : SORT_DESC;
Qiang Xue committed
279
			$args[] = $flag;
Qiang Xue committed
280
		}
281
		$args[] = &$array;
Qiang Xue committed
282
		call_user_func_array('array_multisort', $args);
283
	}
Qiang Xue committed
284
}