BaseArrayHelper.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use ArrayAccess;
  9. use Traversable;
  10. use Yii;
  11. use yii\base\Arrayable;
  12. use yii\base\InvalidArgumentException;
  13. /**
  14. * BaseArrayHelper provides concrete implementation for [[ArrayHelper]].
  15. *
  16. * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class BaseArrayHelper
  22. {
  23. /**
  24. * Converts an object or an array of objects into an array.
  25. * @param object|array|string $object the object to be converted into an array
  26. * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
  27. * The properties specified for each class is an array of the following format:
  28. *
  29. * ```php
  30. * [
  31. * 'app\models\Post' => [
  32. * 'id',
  33. * 'title',
  34. * // the key name in array result => property name
  35. * 'createTime' => 'created_at',
  36. * // the key name in array result => anonymous function
  37. * 'length' => function ($post) {
  38. * return strlen($post->content);
  39. * },
  40. * ],
  41. * ]
  42. * ```
  43. *
  44. * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
  45. *
  46. * ```php
  47. * [
  48. * 'id' => 123,
  49. * 'title' => 'test',
  50. * 'createTime' => '2013-01-01 12:00AM',
  51. * 'length' => 301,
  52. * ]
  53. * ```
  54. *
  55. * @param bool $recursive whether to recursively converts properties which are objects into arrays.
  56. * @return array the array representation of the object
  57. */
  58. public static function toArray($object, $properties = [], $recursive = true)
  59. {
  60. if (is_array($object)) {
  61. if ($recursive) {
  62. foreach ($object as $key => $value) {
  63. if (is_array($value) || is_object($value)) {
  64. $object[$key] = static::toArray($value, $properties, true);
  65. }
  66. }
  67. }
  68. return $object;
  69. } elseif (is_object($object)) {
  70. if (!empty($properties)) {
  71. $className = get_class($object);
  72. if (!empty($properties[$className])) {
  73. $result = [];
  74. foreach ($properties[$className] as $key => $name) {
  75. if (is_int($key)) {
  76. $result[$name] = $object->$name;
  77. } else {
  78. $result[$key] = static::getValue($object, $name);
  79. }
  80. }
  81. return $recursive ? static::toArray($result, $properties) : $result;
  82. }
  83. }
  84. if ($object instanceof Arrayable) {
  85. $result = $object->toArray([], [], $recursive);
  86. } else {
  87. $result = [];
  88. foreach ($object as $key => $value) {
  89. $result[$key] = $value;
  90. }
  91. }
  92. return $recursive ? static::toArray($result, $properties) : $result;
  93. }
  94. return [$object];
  95. }
  96. /**
  97. * Merges two or more arrays into one recursively.
  98. * If each array has an element with the same string key value, the latter
  99. * will overwrite the former (different from array_merge_recursive).
  100. * Recursive merging will be conducted if both arrays have an element of array
  101. * type and are having the same key.
  102. * For integer-keyed elements, the elements from the latter array will
  103. * be appended to the former array.
  104. * You can use [[UnsetArrayValue]] object to unset value from previous array or
  105. * [[ReplaceArrayValue]] to force replace former value instead of recursive merging.
  106. * @param array $a array to be merged to
  107. * @param array $b array to be merged from. You can specify additional
  108. * arrays via third argument, fourth argument etc.
  109. * @return array the merged array (the original arrays are not changed.)
  110. */
  111. public static function merge($a, $b)
  112. {
  113. $args = func_get_args();
  114. $res = array_shift($args);
  115. while (!empty($args)) {
  116. foreach (array_shift($args) as $k => $v) {
  117. if ($v instanceof UnsetArrayValue) {
  118. unset($res[$k]);
  119. } elseif ($v instanceof ReplaceArrayValue) {
  120. $res[$k] = $v->value;
  121. } elseif (is_int($k)) {
  122. if (array_key_exists($k, $res)) {
  123. $res[] = $v;
  124. } else {
  125. $res[$k] = $v;
  126. }
  127. } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
  128. $res[$k] = static::merge($res[$k], $v);
  129. } else {
  130. $res[$k] = $v;
  131. }
  132. }
  133. }
  134. return $res;
  135. }
  136. /**
  137. * Retrieves the value of an array element or object property with the given key or property name.
  138. * If the key does not exist in the array, the default value will be returned instead.
  139. * Not used when getting value from an object.
  140. *
  141. * The key may be specified in a dot format to retrieve the value of a sub-array or the property
  142. * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
  143. * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
  144. * or `$array->x` is neither an array nor an object, the default value will be returned.
  145. * Note that if the array already has an element `x.y.z`, then its value will be returned
  146. * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
  147. * like `['x', 'y', 'z']`.
  148. *
  149. * Below are some usage examples,
  150. *
  151. * ```php
  152. * // working with array
  153. * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
  154. * // working with object
  155. * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
  156. * // working with anonymous function
  157. * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
  158. * return $user->firstName . ' ' . $user->lastName;
  159. * });
  160. * // using dot format to retrieve the property of embedded object
  161. * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
  162. * // using an array of keys to retrieve the value
  163. * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
  164. * ```
  165. *
  166. * @param array|object $array array or object to extract value from
  167. * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object,
  168. * or an anonymous function returning the value. The anonymous function signature should be:
  169. * `function($array, $defaultValue)`.
  170. * The possibility to pass an array of keys is available since version 2.0.4.
  171. * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
  172. * getting value from an object.
  173. * @return mixed the value of the element if found, default value otherwise
  174. */
  175. public static function getValue($array, $key, $default = null)
  176. {
  177. if ($key instanceof \Closure) {
  178. return $key($array, $default);
  179. }
  180. if (is_array($key)) {
  181. $lastKey = array_pop($key);
  182. foreach ($key as $keyPart) {
  183. $array = static::getValue($array, $keyPart);
  184. }
  185. $key = $lastKey;
  186. }
  187. if (is_object($array) && property_exists($array, $key)) {
  188. return $array->$key;
  189. }
  190. if (static::keyExists($key, $array)) {
  191. return $array[$key];
  192. }
  193. if (($pos = strrpos($key, '.')) !== false) {
  194. $array = static::getValue($array, substr($key, 0, $pos), $default);
  195. $key = substr($key, $pos + 1);
  196. }
  197. if (static::keyExists($key, $array)) {
  198. return $array[$key];
  199. }
  200. if (is_object($array)) {
  201. // this is expected to fail if the property does not exist, or __get() is not implemented
  202. // it is not reliably possible to check whether a property is accessible beforehand
  203. try {
  204. return $array->$key;
  205. } catch (\Exception $e) {
  206. if ($array instanceof ArrayAccess) {
  207. return $default;
  208. }
  209. throw $e;
  210. }
  211. }
  212. return $default;
  213. }
  214. /**
  215. * Writes a value into an associative array at the key path specified.
  216. * If there is no such key path yet, it will be created recursively.
  217. * If the key exists, it will be overwritten.
  218. *
  219. * ```php
  220. * $array = [
  221. * 'key' => [
  222. * 'in' => [
  223. * 'val1',
  224. * 'key' => 'val'
  225. * ]
  226. * ]
  227. * ];
  228. * ```
  229. *
  230. * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
  231. *
  232. * ```php
  233. * [
  234. * 'key' => [
  235. * 'in' => [
  236. * ['arr' => 'val'],
  237. * 'key' => 'val'
  238. * ]
  239. * ]
  240. * ]
  241. *
  242. * ```
  243. *
  244. * The result of
  245. * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
  246. * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
  247. * will be the following:
  248. *
  249. * ```php
  250. * [
  251. * 'key' => [
  252. * 'in' => [
  253. * 'arr' => 'val'
  254. * ]
  255. * ]
  256. * ]
  257. * ```
  258. *
  259. * @param array $array the array to write the value to
  260. * @param string|array|null $path the path of where do you want to write a value to `$array`
  261. * the path can be described by a string when each key should be separated by a dot
  262. * you can also describe the path as an array of keys
  263. * if the path is null then `$array` will be assigned the `$value`
  264. * @param mixed $value the value to be written
  265. * @since 2.0.13
  266. */
  267. public static function setValue(&$array, $path, $value)
  268. {
  269. if ($path === null) {
  270. $array = $value;
  271. return;
  272. }
  273. $keys = is_array($path) ? $path : explode('.', $path);
  274. while (count($keys) > 1) {
  275. $key = array_shift($keys);
  276. if (!isset($array[$key])) {
  277. $array[$key] = [];
  278. }
  279. if (!is_array($array[$key])) {
  280. $array[$key] = [$array[$key]];
  281. }
  282. $array = &$array[$key];
  283. }
  284. $array[array_shift($keys)] = $value;
  285. }
  286. /**
  287. * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
  288. * will be returned instead.
  289. *
  290. * Usage examples,
  291. *
  292. * ```php
  293. * // $array = ['type' => 'A', 'options' => [1, 2]];
  294. * // working with array
  295. * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
  296. * // $array content
  297. * // $array = ['options' => [1, 2]];
  298. * ```
  299. *
  300. * @param array $array the array to extract value from
  301. * @param string $key key name of the array element
  302. * @param mixed $default the default value to be returned if the specified key does not exist
  303. * @return mixed|null the value of the element if found, default value otherwise
  304. */
  305. public static function remove(&$array, $key, $default = null)
  306. {
  307. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  308. $value = $array[$key];
  309. unset($array[$key]);
  310. return $value;
  311. }
  312. return $default;
  313. }
  314. /**
  315. * Removes items with matching values from the array and returns the removed items.
  316. *
  317. * Example,
  318. *
  319. * ```php
  320. * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
  321. * $removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
  322. * // result:
  323. * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
  324. * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
  325. * ```
  326. *
  327. * @param array $array the array where to look the value from
  328. * @param string $value the value to remove from the array
  329. * @return array the items that were removed from the array
  330. * @since 2.0.11
  331. */
  332. public static function removeValue(&$array, $value)
  333. {
  334. $result = [];
  335. if (is_array($array)) {
  336. foreach ($array as $key => $val) {
  337. if ($val === $value) {
  338. $result[$key] = $val;
  339. unset($array[$key]);
  340. }
  341. }
  342. }
  343. return $result;
  344. }
  345. /**
  346. * Indexes and/or groups the array according to a specified key.
  347. * The input should be either multidimensional array or an array of objects.
  348. *
  349. * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
  350. * function that must return the value that will be used as a key.
  351. *
  352. * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
  353. * on keys specified.
  354. *
  355. * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
  356. * to `$groups` not specified then the element is discarded.
  357. *
  358. * For example:
  359. *
  360. * ```php
  361. * $array = [
  362. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  363. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  364. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  365. * ];
  366. * $result = ArrayHelper::index($array, 'id');
  367. * ```
  368. *
  369. * The result will be an associative array, where the key is the value of `id` attribute
  370. *
  371. * ```php
  372. * [
  373. * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  374. * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  375. * // The second element of an original array is overwritten by the last element because of the same id
  376. * ]
  377. * ```
  378. *
  379. * An anonymous function can be used in the grouping array as well.
  380. *
  381. * ```php
  382. * $result = ArrayHelper::index($array, function ($element) {
  383. * return $element['id'];
  384. * });
  385. * ```
  386. *
  387. * Passing `id` as a third argument will group `$array` by `id`:
  388. *
  389. * ```php
  390. * $result = ArrayHelper::index($array, null, 'id');
  391. * ```
  392. *
  393. * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
  394. * and indexed by `data` on the third level:
  395. *
  396. * ```php
  397. * [
  398. * '123' => [
  399. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  400. * ],
  401. * '345' => [ // all elements with this index are present in the result array
  402. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  403. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  404. * ]
  405. * ]
  406. * ```
  407. *
  408. * The anonymous function can be used in the array of grouping keys as well:
  409. *
  410. * ```php
  411. * $result = ArrayHelper::index($array, 'data', [function ($element) {
  412. * return $element['id'];
  413. * }, 'device']);
  414. * ```
  415. *
  416. * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
  417. * and indexed by the `data` on the third level:
  418. *
  419. * ```php
  420. * [
  421. * '123' => [
  422. * 'laptop' => [
  423. * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  424. * ]
  425. * ],
  426. * '345' => [
  427. * 'tablet' => [
  428. * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
  429. * ],
  430. * 'smartphone' => [
  431. * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  432. * ]
  433. * ]
  434. * ]
  435. * ```
  436. *
  437. * @param array $array the array that needs to be indexed or grouped
  438. * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
  439. * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
  440. * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
  441. * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
  442. * to the result array without any key. This parameter is available since version 2.0.8.
  443. * @return array the indexed and/or grouped array
  444. */
  445. public static function index($array, $key, $groups = [])
  446. {
  447. $result = [];
  448. $groups = (array) $groups;
  449. foreach ($array as $element) {
  450. $lastArray = &$result;
  451. foreach ($groups as $group) {
  452. $value = static::getValue($element, $group);
  453. if (!array_key_exists($value, $lastArray)) {
  454. $lastArray[$value] = [];
  455. }
  456. $lastArray = &$lastArray[$value];
  457. }
  458. if ($key === null) {
  459. if (!empty($groups)) {
  460. $lastArray[] = $element;
  461. }
  462. } else {
  463. $value = static::getValue($element, $key);
  464. if ($value !== null) {
  465. if (is_float($value)) {
  466. $value = StringHelper::floatToString($value);
  467. }
  468. $lastArray[$value] = $element;
  469. }
  470. }
  471. unset($lastArray);
  472. }
  473. return $result;
  474. }
  475. /**
  476. * Returns the values of a specified column in an array.
  477. * The input array should be multidimensional or an array of objects.
  478. *
  479. * For example,
  480. *
  481. * ```php
  482. * $array = [
  483. * ['id' => '123', 'data' => 'abc'],
  484. * ['id' => '345', 'data' => 'def'],
  485. * ];
  486. * $result = ArrayHelper::getColumn($array, 'id');
  487. * // the result is: ['123', '345']
  488. *
  489. * // using anonymous function
  490. * $result = ArrayHelper::getColumn($array, function ($element) {
  491. * return $element['id'];
  492. * });
  493. * ```
  494. *
  495. * @param array $array
  496. * @param int|string|array|\Closure $name
  497. * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
  498. * will be re-indexed with integers.
  499. * @return array the list of column values
  500. */
  501. public static function getColumn($array, $name, $keepKeys = true)
  502. {
  503. $result = [];
  504. if ($keepKeys) {
  505. foreach ($array as $k => $element) {
  506. $result[$k] = static::getValue($element, $name);
  507. }
  508. } else {
  509. foreach ($array as $element) {
  510. $result[] = static::getValue($element, $name);
  511. }
  512. }
  513. return $result;
  514. }
  515. /**
  516. * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
  517. * The `$from` and `$to` parameters specify the key names or property names to set up the map.
  518. * Optionally, one can further group the map according to a grouping field `$group`.
  519. *
  520. * For example,
  521. *
  522. * ```php
  523. * $array = [
  524. * ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
  525. * ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
  526. * ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
  527. * ];
  528. *
  529. * $result = ArrayHelper::map($array, 'id', 'name');
  530. * // the result is:
  531. * // [
  532. * // '123' => 'aaa',
  533. * // '124' => 'bbb',
  534. * // '345' => 'ccc',
  535. * // ]
  536. *
  537. * $result = ArrayHelper::map($array, 'id', 'name', 'class');
  538. * // the result is:
  539. * // [
  540. * // 'x' => [
  541. * // '123' => 'aaa',
  542. * // '124' => 'bbb',
  543. * // ],
  544. * // 'y' => [
  545. * // '345' => 'ccc',
  546. * // ],
  547. * // ]
  548. * ```
  549. *
  550. * @param array $array
  551. * @param string|\Closure $from
  552. * @param string|\Closure $to
  553. * @param string|\Closure $group
  554. * @return array
  555. */
  556. public static function map($array, $from, $to, $group = null)
  557. {
  558. $result = [];
  559. foreach ($array as $element) {
  560. $key = static::getValue($element, $from);
  561. $value = static::getValue($element, $to);
  562. if ($group !== null) {
  563. $result[static::getValue($element, $group)][$key] = $value;
  564. } else {
  565. $result[$key] = $value;
  566. }
  567. }
  568. return $result;
  569. }
  570. /**
  571. * Checks if the given array contains the specified key.
  572. * This method enhances the `array_key_exists()` function by supporting case-insensitive
  573. * key comparison.
  574. * @param string $key the key to check
  575. * @param array|ArrayAccess $array the array with keys to check
  576. * @param bool $caseSensitive whether the key comparison should be case-sensitive
  577. * @return bool whether the array contains the specified key
  578. */
  579. public static function keyExists($key, $array, $caseSensitive = true)
  580. {
  581. if ($caseSensitive) {
  582. // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
  583. // https://secure.php.net/manual/en/function.array-key-exists.php#107786
  584. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  585. return true;
  586. }
  587. // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
  588. return $array instanceof ArrayAccess && $array->offsetExists($key);
  589. }
  590. if ($array instanceof ArrayAccess) {
  591. throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
  592. }
  593. foreach (array_keys($array) as $k) {
  594. if (strcasecmp($key, $k) === 0) {
  595. return true;
  596. }
  597. }
  598. return false;
  599. }
  600. /**
  601. * Sorts an array of objects or arrays (with the same structure) by one or several keys.
  602. * @param array $array the array to be sorted. The array will be modified after calling this method.
  603. * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
  604. * elements, a property name of the objects, or an anonymous function returning the values for comparison
  605. * purpose. The anonymous function signature should be: `function($item)`.
  606. * To sort by multiple keys, provide an array of keys here.
  607. * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
  608. * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
  609. * @param int|array $sortFlag the PHP sort flag. Valid values include
  610. * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
  611. * Please refer to [PHP manual](https://secure.php.net/manual/en/function.sort.php)
  612. * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
  613. * @throws InvalidArgumentException if the $direction or $sortFlag parameters do not have
  614. * correct number of elements as that of $key.
  615. */
  616. public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
  617. {
  618. $keys = is_array($key) ? $key : [$key];
  619. if (empty($keys) || empty($array)) {
  620. return;
  621. }
  622. $n = count($keys);
  623. if (is_scalar($direction)) {
  624. $direction = array_fill(0, $n, $direction);
  625. } elseif (count($direction) !== $n) {
  626. throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
  627. }
  628. if (is_scalar($sortFlag)) {
  629. $sortFlag = array_fill(0, $n, $sortFlag);
  630. } elseif (count($sortFlag) !== $n) {
  631. throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
  632. }
  633. $args = [];
  634. foreach ($keys as $i => $k) {
  635. $flag = $sortFlag[$i];
  636. $args[] = static::getColumn($array, $k);
  637. $args[] = $direction[$i];
  638. $args[] = $flag;
  639. }
  640. // This fix is used for cases when main sorting specified by columns has equal values
  641. // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
  642. $args[] = range(1, count($array));
  643. $args[] = SORT_ASC;
  644. $args[] = SORT_NUMERIC;
  645. $args[] = &$array;
  646. call_user_func_array('array_multisort', $args);
  647. }
  648. /**
  649. * Encodes special characters in an array of strings into HTML entities.
  650. * Only array values will be encoded by default.
  651. * If a value is an array, this method will also encode it recursively.
  652. * Only string values will be encoded.
  653. * @param array $data data to be encoded
  654. * @param bool $valuesOnly whether to encode array values only. If false,
  655. * both the array keys and array values will be encoded.
  656. * @param string $charset the charset that the data is using. If not set,
  657. * [[\yii\base\Application::charset]] will be used.
  658. * @return array the encoded data
  659. * @see https://secure.php.net/manual/en/function.htmlspecialchars.php
  660. */
  661. public static function htmlEncode($data, $valuesOnly = true, $charset = null)
  662. {
  663. if ($charset === null) {
  664. $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
  665. }
  666. $d = [];
  667. foreach ($data as $key => $value) {
  668. if (!$valuesOnly && is_string($key)) {
  669. $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  670. }
  671. if (is_string($value)) {
  672. $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  673. } elseif (is_array($value)) {
  674. $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
  675. } else {
  676. $d[$key] = $value;
  677. }
  678. }
  679. return $d;
  680. }
  681. /**
  682. * Decodes HTML entities into the corresponding characters in an array of strings.
  683. * Only array values will be decoded by default.
  684. * If a value is an array, this method will also decode it recursively.
  685. * Only string values will be decoded.
  686. * @param array $data data to be decoded
  687. * @param bool $valuesOnly whether to decode array values only. If false,
  688. * both the array keys and array values will be decoded.
  689. * @return array the decoded data
  690. * @see https://secure.php.net/manual/en/function.htmlspecialchars-decode.php
  691. */
  692. public static function htmlDecode($data, $valuesOnly = true)
  693. {
  694. $d = [];
  695. foreach ($data as $key => $value) {
  696. if (!$valuesOnly && is_string($key)) {
  697. $key = htmlspecialchars_decode($key, ENT_QUOTES);
  698. }
  699. if (is_string($value)) {
  700. $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
  701. } elseif (is_array($value)) {
  702. $d[$key] = static::htmlDecode($value);
  703. } else {
  704. $d[$key] = $value;
  705. }
  706. }
  707. return $d;
  708. }
  709. /**
  710. * Returns a value indicating whether the given array is an associative array.
  711. *
  712. * An array is associative if all its keys are strings. If `$allStrings` is false,
  713. * then an array will be treated as associative if at least one of its keys is a string.
  714. *
  715. * Note that an empty array will NOT be considered associative.
  716. *
  717. * @param array $array the array being checked
  718. * @param bool $allStrings whether the array keys must be all strings in order for
  719. * the array to be treated as associative.
  720. * @return bool whether the array is associative
  721. */
  722. public static function isAssociative($array, $allStrings = true)
  723. {
  724. if (!is_array($array) || empty($array)) {
  725. return false;
  726. }
  727. if ($allStrings) {
  728. foreach ($array as $key => $value) {
  729. if (!is_string($key)) {
  730. return false;
  731. }
  732. }
  733. return true;
  734. }
  735. foreach ($array as $key => $value) {
  736. if (is_string($key)) {
  737. return true;
  738. }
  739. }
  740. return false;
  741. }
  742. /**
  743. * Returns a value indicating whether the given array is an indexed array.
  744. *
  745. * An array is indexed if all its keys are integers. If `$consecutive` is true,
  746. * then the array keys must be a consecutive sequence starting from 0.
  747. *
  748. * Note that an empty array will be considered indexed.
  749. *
  750. * @param array $array the array being checked
  751. * @param bool $consecutive whether the array keys must be a consecutive sequence
  752. * in order for the array to be treated as indexed.
  753. * @return bool whether the array is indexed
  754. */
  755. public static function isIndexed($array, $consecutive = false)
  756. {
  757. if (!is_array($array)) {
  758. return false;
  759. }
  760. if (empty($array)) {
  761. return true;
  762. }
  763. if ($consecutive) {
  764. return array_keys($array) === range(0, count($array) - 1);
  765. }
  766. foreach ($array as $key => $value) {
  767. if (!is_int($key)) {
  768. return false;
  769. }
  770. }
  771. return true;
  772. }
  773. /**
  774. * Check whether an array or [[Traversable]] contains an element.
  775. *
  776. * This method does the same as the PHP function [in_array()](https://secure.php.net/manual/en/function.in-array.php)
  777. * but additionally works for objects that implement the [[Traversable]] interface.
  778. * @param mixed $needle The value to look for.
  779. * @param array|Traversable $haystack The set of values to search.
  780. * @param bool $strict Whether to enable strict (`===`) comparison.
  781. * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
  782. * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
  783. * @see https://secure.php.net/manual/en/function.in-array.php
  784. * @since 2.0.7
  785. */
  786. public static function isIn($needle, $haystack, $strict = false)
  787. {
  788. if ($haystack instanceof Traversable) {
  789. foreach ($haystack as $value) {
  790. if ($needle == $value && (!$strict || $needle === $value)) {
  791. return true;
  792. }
  793. }
  794. } elseif (is_array($haystack)) {
  795. return in_array($needle, $haystack, $strict);
  796. } else {
  797. throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
  798. }
  799. return false;
  800. }
  801. /**
  802. * Checks whether a variable is an array or [[Traversable]].
  803. *
  804. * This method does the same as the PHP function [is_array()](https://secure.php.net/manual/en/function.is-array.php)
  805. * but additionally works on objects that implement the [[Traversable]] interface.
  806. * @param mixed $var The variable being evaluated.
  807. * @return bool whether $var can be traversed via foreach
  808. * @see https://secure.php.net/manual/en/function.is-array.php
  809. * @since 2.0.8
  810. */
  811. public static function isTraversable($var)
  812. {
  813. return is_array($var) || $var instanceof Traversable;
  814. }
  815. /**
  816. * Checks whether an array or [[Traversable]] is a subset of another array or [[Traversable]].
  817. *
  818. * This method will return `true`, if all elements of `$needles` are contained in
  819. * `$haystack`. If at least one element is missing, `false` will be returned.
  820. * @param array|Traversable $needles The values that must **all** be in `$haystack`.
  821. * @param array|Traversable $haystack The set of value to search.
  822. * @param bool $strict Whether to enable strict (`===`) comparison.
  823. * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
  824. * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
  825. * @since 2.0.7
  826. */
  827. public static function isSubset($needles, $haystack, $strict = false)
  828. {
  829. if (is_array($needles) || $needles instanceof Traversable) {
  830. foreach ($needles as $needle) {
  831. if (!static::isIn($needle, $haystack, $strict)) {
  832. return false;
  833. }
  834. }
  835. return true;
  836. }
  837. throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
  838. }
  839. /**
  840. * Filters array according to rules specified.
  841. *
  842. * For example:
  843. *
  844. * ```php
  845. * $array = [
  846. * 'A' => [1, 2],
  847. * 'B' => [
  848. * 'C' => 1,
  849. * 'D' => 2,
  850. * ],
  851. * 'E' => 1,
  852. * ];
  853. *
  854. * $result = \yii\helpers\ArrayHelper::filter($array, ['A']);
  855. * // $result will be:
  856. * // [
  857. * // 'A' => [1, 2],
  858. * // ]
  859. *
  860. * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
  861. * // $result will be:
  862. * // [
  863. * // 'A' => [1, 2],
  864. * // 'B' => ['C' => 1],
  865. * // ]
  866. *
  867. * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
  868. * // $result will be:
  869. * // [
  870. * // 'B' => ['D' => 2],
  871. * // ]
  872. * ```
  873. *
  874. * @param array $array Source array
  875. * @param array $filters Rules that define array keys which should be left or removed from results.
  876. * Each rule is:
  877. * - `var` - `$array['var']` will be left in result.
  878. * - `var.key` = only `$array['var']['key'] will be left in result.
  879. * - `!var.key` = `$array['var']['key'] will be removed from result.
  880. * @return array Filtered array
  881. * @since 2.0.9
  882. */
  883. public static function filter($array, $filters)
  884. {
  885. $result = [];
  886. $excludeFilters = [];
  887. foreach ($filters as $filter) {
  888. if (!is_string($filter) && !is_int($filter)) {
  889. continue;
  890. }
  891. if (is_string($filter) && strpos($filter, '!') === 0) {
  892. $excludeFilters[] = substr($filter, 1);
  893. continue;
  894. }
  895. $nodeValue = $array; //set $array as root node
  896. $keys = explode('.', (string) $filter);
  897. foreach ($keys as $key) {
  898. if (!array_key_exists($key, $nodeValue)) {
  899. continue 2; //Jump to next filter
  900. }
  901. $nodeValue = $nodeValue[$key];
  902. }
  903. //We've found a value now let's insert it
  904. $resultNode = &$result;
  905. foreach ($keys as $key) {
  906. if (!array_key_exists($key, $resultNode)) {
  907. $resultNode[$key] = [];
  908. }
  909. $resultNode = &$resultNode[$key];
  910. }
  911. $resultNode = $nodeValue;
  912. }
  913. foreach ($excludeFilters as $filter) {
  914. $excludeNode = &$result;
  915. $keys = explode('.', (string) $filter);
  916. $numNestedKeys = count($keys) - 1;
  917. foreach ($keys as $i => $key) {
  918. if (!array_key_exists($key, $excludeNode)) {
  919. continue 2; //Jump to next filter
  920. }
  921. if ($i < $numNestedKeys) {
  922. $excludeNode = &$excludeNode[$key];
  923. } else {
  924. unset($excludeNode[$key]);
  925. break;
  926. }
  927. }
  928. }
  929. return $result;
  930. }
  931. }