ArrayHelper.php 9.14 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 12
 * @license http://www.yiiframework.com/license/
 */

namespace yii\util;

/**
13 14
 * ArrayHelper provides additional array functionality you can use in your
 * application.
Qiang Xue committed
15 16 17 18
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
19
class ArrayHelper
Qiang Xue committed
20 21
{
	/**
Qiang Xue committed
22
	 * Merges two or more arrays into one recursively.
Qiang Xue committed
23 24 25 26 27 28 29
	 * 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
30 31
	 * @param array $b array to be merged from. You can specify additional
	 * arrays via third argument, fourth argument etc.
Qiang Xue committed
32 33 34 35
	 * @return array the merged array (the original arrays are not changed.)
	 */
	public static function merge($a, $b)
	{
Qiang Xue committed
36 37 38 39 40 41 42 43 44 45 46 47
		$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
48 49
			}
		}
Qiang Xue committed
50
		return $res;
Qiang Xue committed
51 52 53
	}

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

	/**
89 90 91 92 93 94 95 96
	 * 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
97 98 99 100 101 102 103 104 105 106 107
	 * 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'),
108
	 * //     '345' => array('id' => '345', 'data' => 'def'),
Qiang Xue committed
109 110 111 112 113 114
	 * // )
	 *
	 * // using anonymous function
	 * $result = ArrayHelper::index($array, function(element) {
	 *     return $element['id'];
	 * });
115
	 * ~~~
Qiang Xue committed
116
	 *
117 118
	 * @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
119
	 * @return array the indexed array
Qiang Xue committed
120 121 122 123
	 */
	public static function index($array, $key)
	{
		$result = array();
Qiang Xue committed
124
		foreach ($array as $element) {
Qiang Xue committed
125
			$value = static::getValue($element, $key);
Qiang Xue committed
126
			$result[$value] = $element;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
		}
		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
142
	 * $result = ArrayHelper::getColumn($array, 'id');
143 144 145
	 * // the result is: array( '123', '345')
	 *
	 * // using anonymous function
Qiang Xue committed
146
	 * $result = ArrayHelper::getColumn($array, function(element) {
147 148 149 150 151
	 *     return $element['id'];
	 * });
	 * ~~~
	 *
	 * @param array $array
Qiang Xue committed
152 153 154
	 * @param string|\Closure $name
	 * @param boolean $keepKeys whether to maintain the array keys. If false, the resulting array
	 * will be re-indexed with integers.
155 156
	 * @return array the list of column values
	 */
Qiang Xue committed
157
	public static function getColumn($array, $name, $keepKeys = true)
158 159
	{
		$result = array();
Qiang Xue committed
160 161 162 163 164 165 166 167
		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
168
		}
Qiang Xue committed
169

Qiang Xue committed
170 171
		return $result;
	}
172 173 174 175

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

	/**
Qiang Xue committed
230 231 232 233 234 235 236 237 238 239 240
	 * 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
241
	 * See [PHP manual](http://php.net/manual/en/function.sort.php) for more details.
Qiang Xue committed
242 243 244
	 * When sorting by multiple keys with different sort flags, use an array of sort flags.
	 * @throws \yii\base\BadParamException if the $ascending or $sortFlag parameters do not have
	 * correct number of elements as that of $key.
245
	 */
246
	public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR)
247
	{
Qiang Xue committed
248 249 250
		$keys = is_array($key) ? $key : array($key);
		if (empty($keys) || empty($array)) {
			return;
251
		}
Qiang Xue committed
252 253 254 255 256
		$n = count($keys);
		if (is_scalar($ascending)) {
			$ascending = array_fill(0, $n, $ascending);
		} elseif (count($ascending) !== $n) {
			throw new \yii\base\BadParamException('The length of $ascending parameter must be the same as that of $keys.');
257
		}
Qiang Xue committed
258 259 260 261
		if (is_scalar($sortFlag)) {
			$sortFlag = array_fill(0, $n, $sortFlag);
		} elseif (count($sortFlag) !== $n) {
			throw new \yii\base\BadParamException('The length of $ascending parameter must be the same as that of $keys.');
Qiang Xue committed
262
		}
Qiang Xue committed
263 264 265 266 267 268 269 270 271 272 273 274 275
		$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);
			}
276
			$args[] = $ascending[$i] ? SORT_ASC : SORT_DESC;
Qiang Xue committed
277
			$args[] = $flag;
Qiang Xue committed
278
		}
279
		$args[] = &$array;
Qiang Xue committed
280
		call_user_func_array('array_multisort', $args);
281
	}
Qiang Xue committed
282
}