ArrayHelper.php 11.1 KB
Newer Older
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
4 5 6 7 8 9
 * @link http://www.yiiframework.com/
 * @license http://www.yiiframework.com/license/
 */

namespace yii\util;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\InvalidParamException;
Qiang Xue committed
12

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

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

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

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

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

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

	/**
	 * Encodes special characters in an array of strings into HTML entities.
Qiang Xue committed
286
	 * Both the array keys and values will be encoded.
Qiang Xue committed
287 288
	 * If a value is an array, this method will also encode it recursively.
	 * @param array $data data to be encoded
Qiang Xue committed
289 290
	 * @param boolean $valuesOnly whether to encode array values only. If false,
	 * both the array keys and array values will be encoded.
Qiang Xue committed
291 292 293 294 295
	 * @param string $charset the charset that the data is using. If not set,
	 * [[\yii\base\Application::charset]] will be used.
	 * @return array the encoded data
	 * @see http://www.php.net/manual/en/function.htmlspecialchars.php
	 */
Qiang Xue committed
296
	public static function htmlEncode($data, $valuesOnly = false, $charset = null)
Qiang Xue committed
297 298 299 300 301 302
	{
		if ($charset === null) {
			$charset = Yii::$app->charset;
		}
		$d = array();
		foreach ($data as $key => $value) {
Qiang Xue committed
303
			if (!$valuesOnly && is_string($key)) {
Qiang Xue committed
304 305 306
				$key = htmlspecialchars($key, ENT_QUOTES, $charset);
			}
			if (is_string($value)) {
Qiang Xue committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
				$d[$key] = htmlspecialchars($value, ENT_QUOTES, $charset);
			} elseif (is_array($value)) {
				$d[$key] = static::htmlEncode($value, $charset);
			}
		}
		return $d;
	}

	/**
	 * Decodes HTML entities into the corresponding characters in an array of strings.
	 * Both the array keys and values will be decoded.
	 * If a value is an array, this method will also decode it recursively.
	 * @param array $data data to be decoded
	 * @param boolean $valuesOnly whether to decode array values only. If false,
	 * both the array keys and array values will be decoded.
	 * @return array the decoded data
	 * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
	 */
	public static function htmlDecode($data, $valuesOnly = false)
	{
		$d = array();
		foreach ($data as $key => $value) {
			if (!$valuesOnly && is_string($key)) {
				$key = htmlspecialchars_decode($key, ENT_QUOTES);
			}
			if (is_string($value)) {
				$d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
Qiang Xue committed
334
			} elseif (is_array($value)) {
Qiang Xue committed
335
				$d[$key] = static::htmlDecode($value);
Qiang Xue committed
336 337 338 339
			}
		}
		return $d;
	}
Qiang Xue committed
340
}