BaseArrayHelper.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 (static::keyExists($key, $array)) {
  188. return $array[$key];
  189. }
  190. if (($pos = strrpos($key, '.')) !== false) {
  191. $array = static::getValue($array, substr($key, 0, $pos), $default);
  192. $key = substr($key, $pos + 1);
  193. }
  194. if (static::keyExists($key, $array)) {
  195. return $array[$key];
  196. }
  197. if (is_object($array)) {
  198. // this is expected to fail if the property does not exist, or __get() is not implemented
  199. // it is not reliably possible to check whether a property is accessible beforehand
  200. try {
  201. return $array->$key;
  202. } catch (\Exception $e) {
  203. if ($array instanceof ArrayAccess) {
  204. return $default;
  205. }
  206. throw $e;
  207. }
  208. }
  209. return $default;
  210. }
  211. /**
  212. * Writes a value into an associative array at the key path specified.
  213. * If there is no such key path yet, it will be created recursively.
  214. * If the key exists, it will be overwritten.
  215. *
  216. * ```php
  217. * $array = [
  218. * 'key' => [
  219. * 'in' => [
  220. * 'val1',
  221. * 'key' => 'val'
  222. * ]
  223. * ]
  224. * ];
  225. * ```
  226. *
  227. * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
  228. *
  229. * ```php
  230. * [
  231. * 'key' => [
  232. * 'in' => [
  233. * ['arr' => 'val'],
  234. * 'key' => 'val'
  235. * ]
  236. * ]
  237. * ]
  238. *
  239. * ```
  240. *
  241. * The result of
  242. * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
  243. * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
  244. * will be the following:
  245. *
  246. * ```php
  247. * [
  248. * 'key' => [
  249. * 'in' => [
  250. * 'arr' => 'val'
  251. * ]
  252. * ]
  253. * ]
  254. * ```
  255. *
  256. * @param array $array the array to write the value to
  257. * @param string|array|null $path the path of where do you want to write a value to `$array`
  258. * the path can be described by a string when each key should be separated by a dot
  259. * you can also describe the path as an array of keys
  260. * if the path is null then `$array` will be assigned the `$value`
  261. * @param mixed $value the value to be written
  262. * @since 2.0.13
  263. */
  264. public static function setValue(&$array, $path, $value)
  265. {
  266. if ($path === null) {
  267. $array = $value;
  268. return;
  269. }
  270. $keys = is_array($path) ? $path : explode('.', $path);
  271. while (count($keys) > 1) {
  272. $key = array_shift($keys);
  273. if (!isset($array[$key])) {
  274. $array[$key] = [];
  275. }
  276. if (!is_array($array[$key])) {
  277. $array[$key] = [$array[$key]];
  278. }
  279. $array = &$array[$key];
  280. }
  281. $array[array_shift($keys)] = $value;
  282. }
  283. /**
  284. * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
  285. * will be returned instead.
  286. *
  287. * Usage examples,
  288. *
  289. * ```php
  290. * // $array = ['type' => 'A', 'options' => [1, 2]];
  291. * // working with array
  292. * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
  293. * // $array content
  294. * // $array = ['options' => [1, 2]];
  295. * ```
  296. *
  297. * @param array $array the array to extract value from
  298. * @param string $key key name of the array element
  299. * @param mixed $default the default value to be returned if the specified key does not exist
  300. * @return mixed|null the value of the element if found, default value otherwise
  301. */
  302. public static function remove(&$array, $key, $default = null)
  303. {
  304. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  305. $value = $array[$key];
  306. unset($array[$key]);
  307. return $value;
  308. }
  309. return $default;
  310. }
  311. /**
  312. * Removes items with matching values from the array and returns the removed items.
  313. *
  314. * Example,
  315. *
  316. * ```php
  317. * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
  318. * $removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
  319. * // result:
  320. * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
  321. * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
  322. * ```
  323. *
  324. * @param array $array the array where to look the value from
  325. * @param string $value the value to remove from the array
  326. * @return array the items that were removed from the array
  327. * @since 2.0.11
  328. */
  329. public static function removeValue(&$array, $value)
  330. {
  331. $result = [];
  332. if (is_array($array)) {
  333. foreach ($array as $key => $val) {
  334. if ($val === $value) {
  335. $result[$key] = $val;
  336. unset($array[$key]);
  337. }
  338. }
  339. }
  340. return $result;
  341. }
  342. /**
  343. * Indexes and/or groups the array according to a specified key.
  344. * The input should be either multidimensional array or an array of objects.
  345. *
  346. * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
  347. * function that must return the value that will be used as a key.
  348. *
  349. * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
  350. * on keys specified.
  351. *
  352. * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
  353. * to `$groups` not specified then the element is discarded.
  354. *
  355. * For example:
  356. *
  357. * ```php
  358. * $array = [
  359. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  360. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  361. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  362. * ];
  363. * $result = ArrayHelper::index($array, 'id');
  364. * ```
  365. *
  366. * The result will be an associative array, where the key is the value of `id` attribute
  367. *
  368. * ```php
  369. * [
  370. * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  371. * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  372. * // The second element of an original array is overwritten by the last element because of the same id
  373. * ]
  374. * ```
  375. *
  376. * An anonymous function can be used in the grouping array as well.
  377. *
  378. * ```php
  379. * $result = ArrayHelper::index($array, function ($element) {
  380. * return $element['id'];
  381. * });
  382. * ```
  383. *
  384. * Passing `id` as a third argument will group `$array` by `id`:
  385. *
  386. * ```php
  387. * $result = ArrayHelper::index($array, null, 'id');
  388. * ```
  389. *
  390. * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
  391. * and indexed by `data` on the third level:
  392. *
  393. * ```php
  394. * [
  395. * '123' => [
  396. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  397. * ],
  398. * '345' => [ // all elements with this index are present in the result array
  399. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  400. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  401. * ]
  402. * ]
  403. * ```
  404. *
  405. * The anonymous function can be used in the array of grouping keys as well:
  406. *
  407. * ```php
  408. * $result = ArrayHelper::index($array, 'data', [function ($element) {
  409. * return $element['id'];
  410. * }, 'device']);
  411. * ```
  412. *
  413. * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
  414. * and indexed by the `data` on the third level:
  415. *
  416. * ```php
  417. * [
  418. * '123' => [
  419. * 'laptop' => [
  420. * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  421. * ]
  422. * ],
  423. * '345' => [
  424. * 'tablet' => [
  425. * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
  426. * ],
  427. * 'smartphone' => [
  428. * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  429. * ]
  430. * ]
  431. * ]
  432. * ```
  433. *
  434. * @param array $array the array that needs to be indexed or grouped
  435. * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
  436. * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
  437. * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
  438. * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
  439. * to the result array without any key. This parameter is available since version 2.0.8.
  440. * @return array the indexed and/or grouped array
  441. */
  442. public static function index($array, $key, $groups = [])
  443. {
  444. $result = [];
  445. $groups = (array) $groups;
  446. foreach ($array as $element) {
  447. $lastArray = &$result;
  448. foreach ($groups as $group) {
  449. $value = static::getValue($element, $group);
  450. if (!array_key_exists($value, $lastArray)) {
  451. $lastArray[$value] = [];
  452. }
  453. $lastArray = &$lastArray[$value];
  454. }
  455. if ($key === null) {
  456. if (!empty($groups)) {
  457. $lastArray[] = $element;
  458. }
  459. } else {
  460. $value = static::getValue($element, $key);
  461. if ($value !== null) {
  462. if (is_float($value)) {
  463. $value = StringHelper::floatToString($value);
  464. }
  465. $lastArray[$value] = $element;
  466. }
  467. }
  468. unset($lastArray);
  469. }
  470. return $result;
  471. }
  472. /**
  473. * Returns the values of a specified column in an array.
  474. * The input array should be multidimensional or an array of objects.
  475. *
  476. * For example,
  477. *
  478. * ```php
  479. * $array = [
  480. * ['id' => '123', 'data' => 'abc'],
  481. * ['id' => '345', 'data' => 'def'],
  482. * ];
  483. * $result = ArrayHelper::getColumn($array, 'id');
  484. * // the result is: ['123', '345']
  485. *
  486. * // using anonymous function
  487. * $result = ArrayHelper::getColumn($array, function ($element) {
  488. * return $element['id'];
  489. * });
  490. * ```
  491. *
  492. * @param array $array
  493. * @param int|string|\Closure $name
  494. * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
  495. * will be re-indexed with integers.
  496. * @return array the list of column values
  497. */
  498. public static function getColumn($array, $name, $keepKeys = true)
  499. {
  500. $result = [];
  501. if ($keepKeys) {
  502. foreach ($array as $k => $element) {
  503. $result[$k] = static::getValue($element, $name);
  504. }
  505. } else {
  506. foreach ($array as $element) {
  507. $result[] = static::getValue($element, $name);
  508. }
  509. }
  510. return $result;
  511. }
  512. /**
  513. * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
  514. * The `$from` and `$to` parameters specify the key names or property names to set up the map.
  515. * Optionally, one can further group the map according to a grouping field `$group`.
  516. *
  517. * For example,
  518. *
  519. * ```php
  520. * $array = [
  521. * ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
  522. * ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
  523. * ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
  524. * ];
  525. *
  526. * $result = ArrayHelper::map($array, 'id', 'name');
  527. * // the result is:
  528. * // [
  529. * // '123' => 'aaa',
  530. * // '124' => 'bbb',
  531. * // '345' => 'ccc',
  532. * // ]
  533. *
  534. * $result = ArrayHelper::map($array, 'id', 'name', 'class');
  535. * // the result is:
  536. * // [
  537. * // 'x' => [
  538. * // '123' => 'aaa',
  539. * // '124' => 'bbb',
  540. * // ],
  541. * // 'y' => [
  542. * // '345' => 'ccc',
  543. * // ],
  544. * // ]
  545. * ```
  546. *
  547. * @param array $array
  548. * @param string|\Closure $from
  549. * @param string|\Closure $to
  550. * @param string|\Closure $group
  551. * @return array
  552. */
  553. public static function map($array, $from, $to, $group = null)
  554. {
  555. $result = [];
  556. foreach ($array as $element) {
  557. $key = static::getValue($element, $from);
  558. $value = static::getValue($element, $to);
  559. if ($group !== null) {
  560. $result[static::getValue($element, $group)][$key] = $value;
  561. } else {
  562. $result[$key] = $value;
  563. }
  564. }
  565. return $result;
  566. }
  567. /**
  568. * Checks if the given array contains the specified key.
  569. * This method enhances the `array_key_exists()` function by supporting case-insensitive
  570. * key comparison.
  571. * @param string $key the key to check
  572. * @param array|ArrayAccess $array the array with keys to check
  573. * @param bool $caseSensitive whether the key comparison should be case-sensitive
  574. * @return bool whether the array contains the specified key
  575. */
  576. public static function keyExists($key, $array, $caseSensitive = true)
  577. {
  578. if ($caseSensitive) {
  579. // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
  580. // https://secure.php.net/manual/en/function.array-key-exists.php#107786
  581. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  582. return true;
  583. }
  584. // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
  585. return $array instanceof ArrayAccess && $array->offsetExists($key);
  586. }
  587. if ($array instanceof ArrayAccess) {
  588. throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
  589. }
  590. foreach (array_keys($array) as $k) {
  591. if (strcasecmp($key, $k) === 0) {
  592. return true;
  593. }
  594. }
  595. return false;
  596. }
  597. /**
  598. * Sorts an array of objects or arrays (with the same structure) by one or several keys.
  599. * @param array $array the array to be sorted. The array will be modified after calling this method.
  600. * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
  601. * elements, a property name of the objects, or an anonymous function returning the values for comparison
  602. * purpose. The anonymous function signature should be: `function($item)`.
  603. * To sort by multiple keys, provide an array of keys here.
  604. * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
  605. * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
  606. * @param int|array $sortFlag the PHP sort flag. Valid values include
  607. * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
  608. * Please refer to [PHP manual](https://secure.php.net/manual/en/function.sort.php)
  609. * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
  610. * @throws InvalidArgumentException if the $direction or $sortFlag parameters do not have
  611. * correct number of elements as that of $key.
  612. */
  613. public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
  614. {
  615. $keys = is_array($key) ? $key : [$key];
  616. if (empty($keys) || empty($array)) {
  617. return;
  618. }
  619. $n = count($keys);
  620. if (is_scalar($direction)) {
  621. $direction = array_fill(0, $n, $direction);
  622. } elseif (count($direction) !== $n) {
  623. throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
  624. }
  625. if (is_scalar($sortFlag)) {
  626. $sortFlag = array_fill(0, $n, $sortFlag);
  627. } elseif (count($sortFlag) !== $n) {
  628. throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
  629. }
  630. $args = [];
  631. foreach ($keys as $i => $k) {
  632. $flag = $sortFlag[$i];
  633. $args[] = static::getColumn($array, $k);
  634. $args[] = $direction[$i];
  635. $args[] = $flag;
  636. }
  637. // This fix is used for cases when main sorting specified by columns has equal values
  638. // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
  639. $args[] = range(1, count($array));
  640. $args[] = SORT_ASC;
  641. $args[] = SORT_NUMERIC;
  642. $args[] = &$array;
  643. call_user_func_array('array_multisort', $args);
  644. }
  645. /**
  646. * Encodes special characters in an array of strings into HTML entities.
  647. * Only array values will be encoded by default.
  648. * If a value is an array, this method will also encode it recursively.
  649. * Only string values will be encoded.
  650. * @param array $data data to be encoded
  651. * @param bool $valuesOnly whether to encode array values only. If false,
  652. * both the array keys and array values will be encoded.
  653. * @param string $charset the charset that the data is using. If not set,
  654. * [[\yii\base\Application::charset]] will be used.
  655. * @return array the encoded data
  656. * @see https://secure.php.net/manual/en/function.htmlspecialchars.php
  657. */
  658. public static function htmlEncode($data, $valuesOnly = true, $charset = null)
  659. {
  660. if ($charset === null) {
  661. $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
  662. }
  663. $d = [];
  664. foreach ($data as $key => $value) {
  665. if (!$valuesOnly && is_string($key)) {
  666. $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  667. }
  668. if (is_string($value)) {
  669. $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  670. } elseif (is_array($value)) {
  671. $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
  672. } else {
  673. $d[$key] = $value;
  674. }
  675. }
  676. return $d;
  677. }
  678. /**
  679. * Decodes HTML entities into the corresponding characters in an array of strings.
  680. * Only array values will be decoded by default.
  681. * If a value is an array, this method will also decode it recursively.
  682. * Only string values will be decoded.
  683. * @param array $data data to be decoded
  684. * @param bool $valuesOnly whether to decode array values only. If false,
  685. * both the array keys and array values will be decoded.
  686. * @return array the decoded data
  687. * @see https://secure.php.net/manual/en/function.htmlspecialchars-decode.php
  688. */
  689. public static function htmlDecode($data, $valuesOnly = true)
  690. {
  691. $d = [];
  692. foreach ($data as $key => $value) {
  693. if (!$valuesOnly && is_string($key)) {
  694. $key = htmlspecialchars_decode($key, ENT_QUOTES);
  695. }
  696. if (is_string($value)) {
  697. $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
  698. } elseif (is_array($value)) {
  699. $d[$key] = static::htmlDecode($value);
  700. } else {
  701. $d[$key] = $value;
  702. }
  703. }
  704. return $d;
  705. }
  706. /**
  707. * Returns a value indicating whether the given array is an associative array.
  708. *
  709. * An array is associative if all its keys are strings. If `$allStrings` is false,
  710. * then an array will be treated as associative if at least one of its keys is a string.
  711. *
  712. * Note that an empty array will NOT be considered associative.
  713. *
  714. * @param array $array the array being checked
  715. * @param bool $allStrings whether the array keys must be all strings in order for
  716. * the array to be treated as associative.
  717. * @return bool whether the array is associative
  718. */
  719. public static function isAssociative($array, $allStrings = true)
  720. {
  721. if (!is_array($array) || empty($array)) {
  722. return false;
  723. }
  724. if ($allStrings) {
  725. foreach ($array as $key => $value) {
  726. if (!is_string($key)) {
  727. return false;
  728. }
  729. }
  730. return true;
  731. }
  732. foreach ($array as $key => $value) {
  733. if (is_string($key)) {
  734. return true;
  735. }
  736. }
  737. return false;
  738. }
  739. /**
  740. * Returns a value indicating whether the given array is an indexed array.
  741. *
  742. * An array is indexed if all its keys are integers. If `$consecutive` is true,
  743. * then the array keys must be a consecutive sequence starting from 0.
  744. *
  745. * Note that an empty array will be considered indexed.
  746. *
  747. * @param array $array the array being checked
  748. * @param bool $consecutive whether the array keys must be a consecutive sequence
  749. * in order for the array to be treated as indexed.
  750. * @return bool whether the array is indexed
  751. */
  752. public static function isIndexed($array, $consecutive = false)
  753. {
  754. if (!is_array($array)) {
  755. return false;
  756. }
  757. if (empty($array)) {
  758. return true;
  759. }
  760. if ($consecutive) {
  761. return array_keys($array) === range(0, count($array) - 1);
  762. }
  763. foreach ($array as $key => $value) {
  764. if (!is_int($key)) {
  765. return false;
  766. }
  767. }
  768. return true;
  769. }
  770. /**
  771. * Check whether an array or [[Traversable]] contains an element.
  772. *
  773. * This method does the same as the PHP function [in_array()](https://secure.php.net/manual/en/function.in-array.php)
  774. * but additionally works for objects that implement the [[Traversable]] interface.
  775. * @param mixed $needle The value to look for.
  776. * @param array|Traversable $haystack The set of values to search.
  777. * @param bool $strict Whether to enable strict (`===`) comparison.
  778. * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
  779. * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
  780. * @see https://secure.php.net/manual/en/function.in-array.php
  781. * @since 2.0.7
  782. */
  783. public static function isIn($needle, $haystack, $strict = false)
  784. {
  785. if ($haystack instanceof Traversable) {
  786. foreach ($haystack as $value) {
  787. if ($needle == $value && (!$strict || $needle === $value)) {
  788. return true;
  789. }
  790. }
  791. } elseif (is_array($haystack)) {
  792. return in_array($needle, $haystack, $strict);
  793. } else {
  794. throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
  795. }
  796. return false;
  797. }
  798. /**
  799. * Checks whether a variable is an array or [[Traversable]].
  800. *
  801. * This method does the same as the PHP function [is_array()](https://secure.php.net/manual/en/function.is-array.php)
  802. * but additionally works on objects that implement the [[Traversable]] interface.
  803. * @param mixed $var The variable being evaluated.
  804. * @return bool whether $var can be traversed via foreach
  805. * @see https://secure.php.net/manual/en/function.is-array.php
  806. * @since 2.0.8
  807. */
  808. public static function isTraversable($var)
  809. {
  810. return is_array($var) || $var instanceof Traversable;
  811. }
  812. /**
  813. * Checks whether an array or [[Traversable]] is a subset of another array or [[Traversable]].
  814. *
  815. * This method will return `true`, if all elements of `$needles` are contained in
  816. * `$haystack`. If at least one element is missing, `false` will be returned.
  817. * @param array|Traversable $needles The values that must **all** be in `$haystack`.
  818. * @param array|Traversable $haystack The set of value to search.
  819. * @param bool $strict Whether to enable strict (`===`) comparison.
  820. * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
  821. * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
  822. * @since 2.0.7
  823. */
  824. public static function isSubset($needles, $haystack, $strict = false)
  825. {
  826. if (is_array($needles) || $needles instanceof Traversable) {
  827. foreach ($needles as $needle) {
  828. if (!static::isIn($needle, $haystack, $strict)) {
  829. return false;
  830. }
  831. }
  832. return true;
  833. }
  834. throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
  835. }
  836. /**
  837. * Filters array according to rules specified.
  838. *
  839. * For example:
  840. *
  841. * ```php
  842. * $array = [
  843. * 'A' => [1, 2],
  844. * 'B' => [
  845. * 'C' => 1,
  846. * 'D' => 2,
  847. * ],
  848. * 'E' => 1,
  849. * ];
  850. *
  851. * $result = \yii\helpers\ArrayHelper::filter($array, ['A']);
  852. * // $result will be:
  853. * // [
  854. * // 'A' => [1, 2],
  855. * // ]
  856. *
  857. * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
  858. * // $result will be:
  859. * // [
  860. * // 'A' => [1, 2],
  861. * // 'B' => ['C' => 1],
  862. * // ]
  863. *
  864. * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
  865. * // $result will be:
  866. * // [
  867. * // 'B' => ['D' => 2],
  868. * // ]
  869. * ```
  870. *
  871. * @param array $array Source array
  872. * @param array $filters Rules that define array keys which should be left or removed from results.
  873. * Each rule is:
  874. * - `var` - `$array['var']` will be left in result.
  875. * - `var.key` = only `$array['var']['key'] will be left in result.
  876. * - `!var.key` = `$array['var']['key'] will be removed from result.
  877. * @return array Filtered array
  878. * @since 2.0.9
  879. */
  880. public static function filter($array, $filters)
  881. {
  882. $result = [];
  883. $excludeFilters = [];
  884. foreach ($filters as $filter) {
  885. if ($filter[0] === '!') {
  886. $excludeFilters[] = substr($filter, 1);
  887. continue;
  888. }
  889. $nodeValue = $array; //set $array as root node
  890. $keys = explode('.', $filter);
  891. foreach ($keys as $key) {
  892. if (!array_key_exists($key, $nodeValue)) {
  893. continue 2; //Jump to next filter
  894. }
  895. $nodeValue = $nodeValue[$key];
  896. }
  897. //We've found a value now let's insert it
  898. $resultNode = &$result;
  899. foreach ($keys as $key) {
  900. if (!array_key_exists($key, $resultNode)) {
  901. $resultNode[$key] = [];
  902. }
  903. $resultNode = &$resultNode[$key];
  904. }
  905. $resultNode = $nodeValue;
  906. }
  907. foreach ($excludeFilters as $filter) {
  908. $excludeNode = &$result;
  909. $keys = explode('.', $filter);
  910. $numNestedKeys = count($keys) - 1;
  911. foreach ($keys as $i => $key) {
  912. if (!array_key_exists($key, $excludeNode)) {
  913. continue 2; //Jump to next filter
  914. }
  915. if ($i < $numNestedKeys) {
  916. $excludeNode = &$excludeNode[$key];
  917. } else {
  918. unset($excludeNode[$key]);
  919. break;
  920. }
  921. }
  922. }
  923. return $result;
  924. }
  925. }