BaseArrayHelper.php 36 KB

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