Arr.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. <?php
  2. namespace Illuminate\Support;
  3. use ArgumentCountError;
  4. use ArrayAccess;
  5. use Illuminate\Support\Traits\Macroable;
  6. use InvalidArgumentException;
  7. class Arr
  8. {
  9. use Macroable;
  10. /**
  11. * Determine whether the given value is array accessible.
  12. *
  13. * @param mixed $value
  14. * @return bool
  15. */
  16. public static function accessible($value)
  17. {
  18. return is_array($value) || $value instanceof ArrayAccess;
  19. }
  20. /**
  21. * Add an element to an array using "dot" notation if it doesn't exist.
  22. *
  23. * @param array $array
  24. * @param string|int|float $key
  25. * @param mixed $value
  26. * @return array
  27. */
  28. public static function add($array, $key, $value)
  29. {
  30. if (is_null(static::get($array, $key))) {
  31. static::set($array, $key, $value);
  32. }
  33. return $array;
  34. }
  35. /**
  36. * Collapse an array of arrays into a single array.
  37. *
  38. * @param iterable $array
  39. * @return array
  40. */
  41. public static function collapse($array)
  42. {
  43. $results = [];
  44. foreach ($array as $values) {
  45. if ($values instanceof Collection) {
  46. $values = $values->all();
  47. } elseif (! is_array($values)) {
  48. continue;
  49. }
  50. $results[] = $values;
  51. }
  52. return array_merge([], ...$results);
  53. }
  54. /**
  55. * Cross join the given arrays, returning all possible permutations.
  56. *
  57. * @param iterable ...$arrays
  58. * @return array
  59. */
  60. public static function crossJoin(...$arrays)
  61. {
  62. $results = [[]];
  63. foreach ($arrays as $index => $array) {
  64. $append = [];
  65. foreach ($results as $product) {
  66. foreach ($array as $item) {
  67. $product[$index] = $item;
  68. $append[] = $product;
  69. }
  70. }
  71. $results = $append;
  72. }
  73. return $results;
  74. }
  75. /**
  76. * Divide an array into two arrays. One with keys and the other with values.
  77. *
  78. * @param array $array
  79. * @return array
  80. */
  81. public static function divide($array)
  82. {
  83. return [array_keys($array), array_values($array)];
  84. }
  85. /**
  86. * Flatten a multi-dimensional associative array with dots.
  87. *
  88. * @param iterable $array
  89. * @param string $prepend
  90. * @return array
  91. */
  92. public static function dot($array, $prepend = '')
  93. {
  94. $results = [];
  95. foreach ($array as $key => $value) {
  96. if (is_array($value) && ! empty($value)) {
  97. $results = array_merge($results, static::dot($value, $prepend.$key.'.'));
  98. } else {
  99. $results[$prepend.$key] = $value;
  100. }
  101. }
  102. return $results;
  103. }
  104. /**
  105. * Convert a flatten "dot" notation array into an expanded array.
  106. *
  107. * @param iterable $array
  108. * @return array
  109. */
  110. public static function undot($array)
  111. {
  112. $results = [];
  113. foreach ($array as $key => $value) {
  114. static::set($results, $key, $value);
  115. }
  116. return $results;
  117. }
  118. /**
  119. * Get all of the given array except for a specified array of keys.
  120. *
  121. * @param array $array
  122. * @param array|string|int|float $keys
  123. * @return array
  124. */
  125. public static function except($array, $keys)
  126. {
  127. static::forget($array, $keys);
  128. return $array;
  129. }
  130. /**
  131. * Determine if the given key exists in the provided array.
  132. *
  133. * @param \ArrayAccess|array $array
  134. * @param string|int $key
  135. * @return bool
  136. */
  137. public static function exists($array, $key)
  138. {
  139. if ($array instanceof Enumerable) {
  140. return $array->has($key);
  141. }
  142. if ($array instanceof ArrayAccess) {
  143. return $array->offsetExists($key);
  144. }
  145. if (is_float($key)) {
  146. $key = (string) $key;
  147. }
  148. return array_key_exists($key, $array);
  149. }
  150. /**
  151. * Return the first element in an array passing a given truth test.
  152. *
  153. * @param iterable $array
  154. * @param callable|null $callback
  155. * @param mixed $default
  156. * @return mixed
  157. */
  158. public static function first($array, ?callable $callback = null, $default = null)
  159. {
  160. if (is_null($callback)) {
  161. if (empty($array)) {
  162. return value($default);
  163. }
  164. foreach ($array as $item) {
  165. return $item;
  166. }
  167. return value($default);
  168. }
  169. foreach ($array as $key => $value) {
  170. if ($callback($value, $key)) {
  171. return $value;
  172. }
  173. }
  174. return value($default);
  175. }
  176. /**
  177. * Return the last element in an array passing a given truth test.
  178. *
  179. * @param array $array
  180. * @param callable|null $callback
  181. * @param mixed $default
  182. * @return mixed
  183. */
  184. public static function last($array, ?callable $callback = null, $default = null)
  185. {
  186. if (is_null($callback)) {
  187. return empty($array) ? value($default) : end($array);
  188. }
  189. return static::first(array_reverse($array, true), $callback, $default);
  190. }
  191. /**
  192. * Take the first or last {$limit} items from an array.
  193. *
  194. * @param array $array
  195. * @param int $limit
  196. * @return array
  197. */
  198. public static function take($array, $limit)
  199. {
  200. if ($limit < 0) {
  201. return array_slice($array, $limit, abs($limit));
  202. }
  203. return array_slice($array, 0, $limit);
  204. }
  205. /**
  206. * Flatten a multi-dimensional array into a single level.
  207. *
  208. * @param iterable $array
  209. * @param int $depth
  210. * @return array
  211. */
  212. public static function flatten($array, $depth = INF)
  213. {
  214. $result = [];
  215. foreach ($array as $item) {
  216. $item = $item instanceof Collection ? $item->all() : $item;
  217. if (! is_array($item)) {
  218. $result[] = $item;
  219. } else {
  220. $values = $depth === 1
  221. ? array_values($item)
  222. : static::flatten($item, $depth - 1);
  223. foreach ($values as $value) {
  224. $result[] = $value;
  225. }
  226. }
  227. }
  228. return $result;
  229. }
  230. /**
  231. * Remove one or many array items from a given array using "dot" notation.
  232. *
  233. * @param array $array
  234. * @param array|string|int|float $keys
  235. * @return void
  236. */
  237. public static function forget(&$array, $keys)
  238. {
  239. $original = &$array;
  240. $keys = (array) $keys;
  241. if (count($keys) === 0) {
  242. return;
  243. }
  244. foreach ($keys as $key) {
  245. // if the exact key exists in the top-level, remove it
  246. if (static::exists($array, $key)) {
  247. unset($array[$key]);
  248. continue;
  249. }
  250. $parts = explode('.', $key);
  251. // clean up before each pass
  252. $array = &$original;
  253. while (count($parts) > 1) {
  254. $part = array_shift($parts);
  255. if (isset($array[$part]) && static::accessible($array[$part])) {
  256. $array = &$array[$part];
  257. } else {
  258. continue 2;
  259. }
  260. }
  261. unset($array[array_shift($parts)]);
  262. }
  263. }
  264. /**
  265. * Get an item from an array using "dot" notation.
  266. *
  267. * @param \ArrayAccess|array $array
  268. * @param string|int|null $key
  269. * @param mixed $default
  270. * @return mixed
  271. */
  272. public static function get($array, $key, $default = null)
  273. {
  274. if (! static::accessible($array)) {
  275. return value($default);
  276. }
  277. if (is_null($key)) {
  278. return $array;
  279. }
  280. if (static::exists($array, $key)) {
  281. return $array[$key];
  282. }
  283. if (! str_contains($key, '.')) {
  284. return $array[$key] ?? value($default);
  285. }
  286. foreach (explode('.', $key) as $segment) {
  287. if (static::accessible($array) && static::exists($array, $segment)) {
  288. $array = $array[$segment];
  289. } else {
  290. return value($default);
  291. }
  292. }
  293. return $array;
  294. }
  295. /**
  296. * Check if an item or items exist in an array using "dot" notation.
  297. *
  298. * @param \ArrayAccess|array $array
  299. * @param string|array $keys
  300. * @return bool
  301. */
  302. public static function has($array, $keys)
  303. {
  304. $keys = (array) $keys;
  305. if (! $array || $keys === []) {
  306. return false;
  307. }
  308. foreach ($keys as $key) {
  309. $subKeyArray = $array;
  310. if (static::exists($array, $key)) {
  311. continue;
  312. }
  313. foreach (explode('.', $key) as $segment) {
  314. if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
  315. $subKeyArray = $subKeyArray[$segment];
  316. } else {
  317. return false;
  318. }
  319. }
  320. }
  321. return true;
  322. }
  323. /**
  324. * Determine if any of the keys exist in an array using "dot" notation.
  325. *
  326. * @param \ArrayAccess|array $array
  327. * @param string|array $keys
  328. * @return bool
  329. */
  330. public static function hasAny($array, $keys)
  331. {
  332. if (is_null($keys)) {
  333. return false;
  334. }
  335. $keys = (array) $keys;
  336. if (! $array) {
  337. return false;
  338. }
  339. if ($keys === []) {
  340. return false;
  341. }
  342. foreach ($keys as $key) {
  343. if (static::has($array, $key)) {
  344. return true;
  345. }
  346. }
  347. return false;
  348. }
  349. /**
  350. * Determines if an array is associative.
  351. *
  352. * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
  353. *
  354. * @param array $array
  355. * @return bool
  356. */
  357. public static function isAssoc(array $array)
  358. {
  359. return ! array_is_list($array);
  360. }
  361. /**
  362. * Determines if an array is a list.
  363. *
  364. * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between.
  365. *
  366. * @param array $array
  367. * @return bool
  368. */
  369. public static function isList($array)
  370. {
  371. return array_is_list($array);
  372. }
  373. /**
  374. * Join all items using a string. The final items can use a separate glue string.
  375. *
  376. * @param array $array
  377. * @param string $glue
  378. * @param string $finalGlue
  379. * @return string
  380. */
  381. public static function join($array, $glue, $finalGlue = '')
  382. {
  383. if ($finalGlue === '') {
  384. return implode($glue, $array);
  385. }
  386. if (count($array) === 0) {
  387. return '';
  388. }
  389. if (count($array) === 1) {
  390. return end($array);
  391. }
  392. $finalItem = array_pop($array);
  393. return implode($glue, $array).$finalGlue.$finalItem;
  394. }
  395. /**
  396. * Key an associative array by a field or using a callback.
  397. *
  398. * @param array $array
  399. * @param callable|array|string $keyBy
  400. * @return array
  401. */
  402. public static function keyBy($array, $keyBy)
  403. {
  404. return Collection::make($array)->keyBy($keyBy)->all();
  405. }
  406. /**
  407. * Prepend the key names of an associative array.
  408. *
  409. * @param array $array
  410. * @param string $prependWith
  411. * @return array
  412. */
  413. public static function prependKeysWith($array, $prependWith)
  414. {
  415. return static::mapWithKeys($array, fn ($item, $key) => [$prependWith.$key => $item]);
  416. }
  417. /**
  418. * Get a subset of the items from the given array.
  419. *
  420. * @param array $array
  421. * @param array|string $keys
  422. * @return array
  423. */
  424. public static function only($array, $keys)
  425. {
  426. return array_intersect_key($array, array_flip((array) $keys));
  427. }
  428. /**
  429. * Select an array of values from an array.
  430. *
  431. * @param array $array
  432. * @param array|string $keys
  433. * @return array
  434. */
  435. public static function select($array, $keys)
  436. {
  437. $keys = static::wrap($keys);
  438. return static::map($array, function ($item) use ($keys) {
  439. $result = [];
  440. foreach ($keys as $key) {
  441. if (Arr::accessible($item) && Arr::exists($item, $key)) {
  442. $result[$key] = $item[$key];
  443. } elseif (is_object($item) && isset($item->{$key})) {
  444. $result[$key] = $item->{$key};
  445. }
  446. }
  447. return $result;
  448. });
  449. }
  450. /**
  451. * Pluck an array of values from an array.
  452. *
  453. * @param iterable $array
  454. * @param string|array|int|null $value
  455. * @param string|array|null $key
  456. * @return array
  457. */
  458. public static function pluck($array, $value, $key = null)
  459. {
  460. $results = [];
  461. [$value, $key] = static::explodePluckParameters($value, $key);
  462. foreach ($array as $item) {
  463. $itemValue = data_get($item, $value);
  464. // If the key is "null", we will just append the value to the array and keep
  465. // looping. Otherwise we will key the array using the value of the key we
  466. // received from the developer. Then we'll return the final array form.
  467. if (is_null($key)) {
  468. $results[] = $itemValue;
  469. } else {
  470. $itemKey = data_get($item, $key);
  471. if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
  472. $itemKey = (string) $itemKey;
  473. }
  474. $results[$itemKey] = $itemValue;
  475. }
  476. }
  477. return $results;
  478. }
  479. /**
  480. * Explode the "value" and "key" arguments passed to "pluck".
  481. *
  482. * @param string|array $value
  483. * @param string|array|null $key
  484. * @return array
  485. */
  486. protected static function explodePluckParameters($value, $key)
  487. {
  488. $value = is_string($value) ? explode('.', $value) : $value;
  489. $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
  490. return [$value, $key];
  491. }
  492. /**
  493. * Run a map over each of the items in the array.
  494. *
  495. * @param array $array
  496. * @param callable $callback
  497. * @return array
  498. */
  499. public static function map(array $array, callable $callback)
  500. {
  501. $keys = array_keys($array);
  502. try {
  503. $items = array_map($callback, $array, $keys);
  504. } catch (ArgumentCountError) {
  505. $items = array_map($callback, $array);
  506. }
  507. return array_combine($keys, $items);
  508. }
  509. /**
  510. * Run an associative map over each of the items.
  511. *
  512. * The callback should return an associative array with a single key/value pair.
  513. *
  514. * @template TKey
  515. * @template TValue
  516. * @template TMapWithKeysKey of array-key
  517. * @template TMapWithKeysValue
  518. *
  519. * @param array<TKey, TValue> $array
  520. * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
  521. * @return array
  522. */
  523. public static function mapWithKeys(array $array, callable $callback)
  524. {
  525. $result = [];
  526. foreach ($array as $key => $value) {
  527. $assoc = $callback($value, $key);
  528. foreach ($assoc as $mapKey => $mapValue) {
  529. $result[$mapKey] = $mapValue;
  530. }
  531. }
  532. return $result;
  533. }
  534. /**
  535. * Push an item onto the beginning of an array.
  536. *
  537. * @param array $array
  538. * @param mixed $value
  539. * @param mixed $key
  540. * @return array
  541. */
  542. public static function prepend($array, $value, $key = null)
  543. {
  544. if (func_num_args() == 2) {
  545. array_unshift($array, $value);
  546. } else {
  547. $array = [$key => $value] + $array;
  548. }
  549. return $array;
  550. }
  551. /**
  552. * Get a value from the array, and remove it.
  553. *
  554. * @param array $array
  555. * @param string|int $key
  556. * @param mixed $default
  557. * @return mixed
  558. */
  559. public static function pull(&$array, $key, $default = null)
  560. {
  561. $value = static::get($array, $key, $default);
  562. static::forget($array, $key);
  563. return $value;
  564. }
  565. /**
  566. * Convert the array into a query string.
  567. *
  568. * @param array $array
  569. * @return string
  570. */
  571. public static function query($array)
  572. {
  573. return http_build_query($array, '', '&', PHP_QUERY_RFC3986);
  574. }
  575. /**
  576. * Get one or a specified number of random values from an array.
  577. *
  578. * @param array $array
  579. * @param int|null $number
  580. * @param bool $preserveKeys
  581. * @return mixed
  582. *
  583. * @throws \InvalidArgumentException
  584. */
  585. public static function random($array, $number = null, $preserveKeys = false)
  586. {
  587. $requested = is_null($number) ? 1 : $number;
  588. $count = count($array);
  589. if ($requested > $count) {
  590. throw new InvalidArgumentException(
  591. "You requested {$requested} items, but there are only {$count} items available."
  592. );
  593. }
  594. if (is_null($number)) {
  595. return $array[array_rand($array)];
  596. }
  597. if ((int) $number === 0) {
  598. return [];
  599. }
  600. $keys = array_rand($array, $number);
  601. $results = [];
  602. if ($preserveKeys) {
  603. foreach ((array) $keys as $key) {
  604. $results[$key] = $array[$key];
  605. }
  606. } else {
  607. foreach ((array) $keys as $key) {
  608. $results[] = $array[$key];
  609. }
  610. }
  611. return $results;
  612. }
  613. /**
  614. * Set an array item to a given value using "dot" notation.
  615. *
  616. * If no key is given to the method, the entire array will be replaced.
  617. *
  618. * @param array $array
  619. * @param string|int|null $key
  620. * @param mixed $value
  621. * @return array
  622. */
  623. public static function set(&$array, $key, $value)
  624. {
  625. if (is_null($key)) {
  626. return $array = $value;
  627. }
  628. $keys = explode('.', $key);
  629. foreach ($keys as $i => $key) {
  630. if (count($keys) === 1) {
  631. break;
  632. }
  633. unset($keys[$i]);
  634. // If the key doesn't exist at this depth, we will just create an empty array
  635. // to hold the next value, allowing us to create the arrays to hold final
  636. // values at the correct depth. Then we'll keep digging into the array.
  637. if (! isset($array[$key]) || ! is_array($array[$key])) {
  638. $array[$key] = [];
  639. }
  640. $array = &$array[$key];
  641. }
  642. $array[array_shift($keys)] = $value;
  643. return $array;
  644. }
  645. /**
  646. * Shuffle the given array and return the result.
  647. *
  648. * @param array $array
  649. * @param int|null $seed
  650. * @return array
  651. */
  652. public static function shuffle($array, $seed = null)
  653. {
  654. if (is_null($seed)) {
  655. shuffle($array);
  656. } else {
  657. mt_srand($seed);
  658. shuffle($array);
  659. mt_srand();
  660. }
  661. return $array;
  662. }
  663. /**
  664. * Sort the array using the given callback or "dot" notation.
  665. *
  666. * @param array $array
  667. * @param callable|array|string|null $callback
  668. * @return array
  669. */
  670. public static function sort($array, $callback = null)
  671. {
  672. return Collection::make($array)->sortBy($callback)->all();
  673. }
  674. /**
  675. * Sort the array in descending order using the given callback or "dot" notation.
  676. *
  677. * @param array $array
  678. * @param callable|array|string|null $callback
  679. * @return array
  680. */
  681. public static function sortDesc($array, $callback = null)
  682. {
  683. return Collection::make($array)->sortByDesc($callback)->all();
  684. }
  685. /**
  686. * Recursively sort an array by keys and values.
  687. *
  688. * @param array $array
  689. * @param int $options
  690. * @param bool $descending
  691. * @return array
  692. */
  693. public static function sortRecursive($array, $options = SORT_REGULAR, $descending = false)
  694. {
  695. foreach ($array as &$value) {
  696. if (is_array($value)) {
  697. $value = static::sortRecursive($value, $options, $descending);
  698. }
  699. }
  700. if (! array_is_list($array)) {
  701. $descending
  702. ? krsort($array, $options)
  703. : ksort($array, $options);
  704. } else {
  705. $descending
  706. ? rsort($array, $options)
  707. : sort($array, $options);
  708. }
  709. return $array;
  710. }
  711. /**
  712. * Recursively sort an array by keys and values in descending order.
  713. *
  714. * @param array $array
  715. * @param int $options
  716. * @return array
  717. */
  718. public static function sortRecursiveDesc($array, $options = SORT_REGULAR)
  719. {
  720. return static::sortRecursive($array, $options, true);
  721. }
  722. /**
  723. * Conditionally compile classes from an array into a CSS class list.
  724. *
  725. * @param array $array
  726. * @return string
  727. */
  728. public static function toCssClasses($array)
  729. {
  730. $classList = static::wrap($array);
  731. $classes = [];
  732. foreach ($classList as $class => $constraint) {
  733. if (is_numeric($class)) {
  734. $classes[] = $constraint;
  735. } elseif ($constraint) {
  736. $classes[] = $class;
  737. }
  738. }
  739. return implode(' ', $classes);
  740. }
  741. /**
  742. * Conditionally compile styles from an array into a style list.
  743. *
  744. * @param array $array
  745. * @return string
  746. */
  747. public static function toCssStyles($array)
  748. {
  749. $styleList = static::wrap($array);
  750. $styles = [];
  751. foreach ($styleList as $class => $constraint) {
  752. if (is_numeric($class)) {
  753. $styles[] = Str::finish($constraint, ';');
  754. } elseif ($constraint) {
  755. $styles[] = Str::finish($class, ';');
  756. }
  757. }
  758. return implode(' ', $styles);
  759. }
  760. /**
  761. * Filter the array using the given callback.
  762. *
  763. * @param array $array
  764. * @param callable $callback
  765. * @return array
  766. */
  767. public static function where($array, callable $callback)
  768. {
  769. return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
  770. }
  771. /**
  772. * Filter items where the value is not null.
  773. *
  774. * @param array $array
  775. * @return array
  776. */
  777. public static function whereNotNull($array)
  778. {
  779. return static::where($array, fn ($value) => ! is_null($value));
  780. }
  781. /**
  782. * If the given value is not an array and not null, wrap it in one.
  783. *
  784. * @param mixed $value
  785. * @return array
  786. */
  787. public static function wrap($value)
  788. {
  789. if (is_null($value)) {
  790. return [];
  791. }
  792. return is_array($value) ? $value : [$value];
  793. }
  794. }