Arr.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. <?php
  2. /**
  3. * Array helper.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) Kohana Team
  9. * @license https://koseven.ga/LICENSE.md
  10. */
  11. class Kohana_Arr {
  12. /**
  13. * @var string default delimiter for path()
  14. */
  15. public static $delimiter = '.';
  16. /**
  17. * Tests if an array is associative or not.
  18. *
  19. * // Returns TRUE
  20. * Arr::is_assoc(array('username' => 'john.doe'));
  21. *
  22. * // Returns FALSE
  23. * Arr::is_assoc('foo', 'bar');
  24. *
  25. * @param array $array array to check
  26. * @return boolean
  27. */
  28. public static function is_assoc(array $array)
  29. {
  30. // Keys of the array
  31. $keys = array_keys($array);
  32. // If the array keys of the keys match the keys, then the array must
  33. // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
  34. return array_keys($keys) !== $keys;
  35. }
  36. /**
  37. * Test if a value is an array with an additional check for array-like objects.
  38. *
  39. * // Returns TRUE
  40. * Arr::is_array(array());
  41. * Arr::is_array(new ArrayObject);
  42. *
  43. * // Returns FALSE
  44. * Arr::is_array(FALSE);
  45. * Arr::is_array('not an array!');
  46. * Arr::is_array(Database::instance());
  47. *
  48. * @param mixed $value value to check
  49. * @return boolean
  50. */
  51. public static function is_array($value)
  52. {
  53. if (is_array($value))
  54. {
  55. // Definitely an array
  56. return TRUE;
  57. }
  58. else
  59. {
  60. // Possibly a Traversable object, functionally the same as an array
  61. return (is_object($value) AND $value instanceof Traversable);
  62. }
  63. }
  64. /**
  65. * Gets a value from an array using a dot separated path.
  66. *
  67. * // Get the value of $array['foo']['bar']
  68. * $value = Arr::path($array, 'foo.bar');
  69. *
  70. * Using a wildcard "*" will search intermediate arrays and return an array.
  71. *
  72. * // Get the values of "color" in theme
  73. * $colors = Arr::path($array, 'theme.*.color');
  74. *
  75. * // Using an array of keys
  76. * $colors = Arr::path($array, array('theme', '*', 'color'));
  77. *
  78. * @param array $array array to search
  79. * @param mixed $path key path string (delimiter separated) or array of keys
  80. * @param mixed $default default value if the path is not set
  81. * @param string $delimiter key path delimiter
  82. * @return mixed
  83. */
  84. public static function path($array, $path, $default = NULL, $delimiter = NULL)
  85. {
  86. if ( ! Arr::is_array($array))
  87. {
  88. // This is not an array!
  89. return $default;
  90. }
  91. if (is_array($path))
  92. {
  93. // The path has already been separated into keys
  94. $keys = $path;
  95. }
  96. else
  97. {
  98. if ((is_object($array) AND property_exists($array, $path)) || (is_array($array) AND array_key_exists($path, $array)))
  99. {
  100. // No need to do extra processing
  101. return $array[$path];
  102. }
  103. if ($delimiter === NULL)
  104. {
  105. // Use the default delimiter
  106. $delimiter = Arr::$delimiter;
  107. }
  108. // Remove starting delimiters and spaces
  109. $path = ltrim($path, "{$delimiter} ");
  110. // Remove ending delimiters, spaces, and wildcards
  111. $path = rtrim($path, "{$delimiter} *");
  112. // Split the keys by delimiter
  113. $keys = explode($delimiter, $path);
  114. }
  115. do
  116. {
  117. $key = array_shift($keys);
  118. if (ctype_digit($key))
  119. {
  120. // Make the key an integer
  121. $key = (int) $key;
  122. }
  123. if (isset($array[$key]))
  124. {
  125. if ($keys)
  126. {
  127. if (Arr::is_array($array[$key]))
  128. {
  129. // Dig down into the next part of the path
  130. $array = $array[$key];
  131. }
  132. else
  133. {
  134. // Unable to dig deeper
  135. break;
  136. }
  137. }
  138. else
  139. {
  140. // Found the path requested
  141. return $array[$key];
  142. }
  143. }
  144. elseif ($key === '*')
  145. {
  146. // Handle wildcards
  147. $values = [];
  148. foreach ($array as $arr)
  149. {
  150. if ($value = Arr::path($arr, implode('.', $keys)))
  151. {
  152. $values[] = $value;
  153. }
  154. }
  155. if ($values)
  156. {
  157. // Found the values requested
  158. return $values;
  159. }
  160. else
  161. {
  162. // Unable to dig deeper
  163. break;
  164. }
  165. }
  166. else
  167. {
  168. // Unable to dig deeper
  169. break;
  170. }
  171. }
  172. while ($keys);
  173. // Unable to find the value requested
  174. return $default;
  175. }
  176. /**
  177. * Set a value on an array by path.
  178. *
  179. * @see Arr::path()
  180. * @param array $array Array to update
  181. * @param string $path Path
  182. * @param mixed $value Value to set
  183. * @param string $delimiter Path delimiter
  184. */
  185. public static function set_path( & $array, $path, $value, $delimiter = NULL)
  186. {
  187. if ( ! $delimiter)
  188. {
  189. // Use the default delimiter
  190. $delimiter = Arr::$delimiter;
  191. }
  192. // The path has already been separated into keys
  193. $keys = $path;
  194. if ( ! is_array($path))
  195. {
  196. // Split the keys by delimiter
  197. $keys = explode($delimiter, $path);
  198. }
  199. // Set current $array to inner-most array path
  200. while (count($keys) > 1)
  201. {
  202. $key = array_shift($keys);
  203. if (ctype_digit($key))
  204. {
  205. // Make the key an integer
  206. $key = (int) $key;
  207. }
  208. if ( ! isset($array[$key]))
  209. {
  210. $array[$key] = [];
  211. }
  212. $array = & $array[$key];
  213. }
  214. // Set key on inner-most array
  215. $array[array_shift($keys)] = $value;
  216. }
  217. /**
  218. * Fill an array with a range of numbers.
  219. *
  220. * // Fill an array with values 5, 10, 15, 20
  221. * $values = Arr::range(5, 20);
  222. *
  223. * @param integer $step stepping
  224. * @param integer $max ending number
  225. * @return array
  226. */
  227. public static function range($step = 10, $max = 100)
  228. {
  229. if ($step < 1)
  230. return [];
  231. $array = [];
  232. for ($i = $step; $i <= $max; $i += $step)
  233. {
  234. $array[$i] = $i;
  235. }
  236. return $array;
  237. }
  238. /**
  239. * Retrieve a single key from an array. If the key does not exist in the
  240. * array, the default value will be returned instead.
  241. *
  242. * // Get the value "username" from $_POST, if it exists
  243. * $username = Arr::get($_POST, 'username');
  244. *
  245. * // Get the value "sorting" from $_GET, if it exists
  246. * $sorting = Arr::get($_GET, 'sorting');
  247. *
  248. * @param array $array array to extract from
  249. * @param string $key key name
  250. * @param mixed $default default value
  251. * @return mixed
  252. */
  253. public static function get($array, $key, $default = NULL)
  254. {
  255. if ($array instanceof ArrayObject) {
  256. // This is a workaround for inconsistent implementation of isset between PHP and HHVM
  257. // See https://github.com/facebook/hhvm/issues/3437
  258. return $array->offsetExists($key) ? $array->offsetGet($key) : $default;
  259. } else {
  260. return isset($array[$key]) ? $array[$key] : $default;
  261. }
  262. }
  263. /**
  264. * Retrieves multiple paths from an array. If the path does not exist in the
  265. * array, the default value will be added instead.
  266. *
  267. * // Get the values "username", "password" from $_POST
  268. * $auth = Arr::extract($_POST, array('username', 'password'));
  269. *
  270. * // Get the value "level1.level2a" from $data
  271. * $data = array('level1' => array('level2a' => 'value 1', 'level2b' => 'value 2'));
  272. * Arr::extract($data, array('level1.level2a', 'password'));
  273. *
  274. * @param array $array array to extract paths from
  275. * @param array $paths list of path
  276. * @param mixed $default default value
  277. * @return array
  278. */
  279. public static function extract($array, array $paths, $default = NULL)
  280. {
  281. $found = [];
  282. foreach ($paths as $path)
  283. {
  284. Arr::set_path($found, $path, Arr::path($array, $path, $default));
  285. }
  286. return $found;
  287. }
  288. /**
  289. * Retrieves muliple single-key values from a list of arrays.
  290. *
  291. * // Get all of the "id" values from a result
  292. * $ids = Arr::pluck($result, 'id');
  293. *
  294. * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
  295. *
  296. * @param array $array list of arrays to check
  297. * @param string $key key to pluck
  298. * @return array
  299. */
  300. public static function pluck($array, $key)
  301. {
  302. $values = [];
  303. foreach ($array as $row)
  304. {
  305. if (isset($row[$key]))
  306. {
  307. // Found a value in this row
  308. $values[] = $row[$key];
  309. }
  310. }
  311. return $values;
  312. }
  313. /**
  314. * Adds a value to the beginning of an associative array.
  315. *
  316. * // Add an empty value to the start of a select list
  317. * Arr::unshift($array, 'none', 'Select a value');
  318. *
  319. * @param array $array array to modify
  320. * @param string $key array key name
  321. * @param mixed $val array value
  322. * @return array
  323. */
  324. public static function unshift( array & $array, $key, $val)
  325. {
  326. $array = array_reverse($array, TRUE);
  327. $array[$key] = $val;
  328. $array = array_reverse($array, TRUE);
  329. return $array;
  330. }
  331. /**
  332. * Recursive version of [array_map](http://php.net/array_map), applies one or more
  333. * callbacks to all elements in an array, including sub-arrays.
  334. *
  335. * // Apply "strip_tags" to every element in the array
  336. * $array = Arr::map('strip_tags', $array);
  337. *
  338. * // Apply $this->filter to every element in the array
  339. * $array = Arr::map(array(array($this,'filter')), $array);
  340. *
  341. * // Apply strip_tags and $this->filter to every element
  342. * $array = Arr::map(array('strip_tags',array($this,'filter')), $array);
  343. *
  344. * [!!] Because you can pass an array of callbacks, if you wish to use an array-form callback
  345. * you must nest it in an additional array as above. Calling Arr::map(array($this,'filter'), $array)
  346. * will cause an error.
  347. * [!!] Unlike `array_map`, this method requires a callback and will only map
  348. * a single array.
  349. *
  350. * @param mixed $callbacks array of callbacks to apply to every element in the array
  351. * @param array $array array to map
  352. * @param array $keys array of keys to apply to
  353. * @return array
  354. */
  355. public static function map($callbacks, $array, $keys = NULL)
  356. {
  357. foreach ($array as $key => $val)
  358. {
  359. if (is_array($val))
  360. {
  361. $array[$key] = Arr::map($callbacks, $array[$key], $keys);
  362. }
  363. elseif ( ! is_array($keys) OR in_array($key, $keys))
  364. {
  365. if (is_array($callbacks))
  366. {
  367. foreach ($callbacks as $cb)
  368. {
  369. $array[$key] = call_user_func($cb, $array[$key]);
  370. }
  371. }
  372. else
  373. {
  374. $array[$key] = call_user_func($callbacks, $array[$key]);
  375. }
  376. }
  377. }
  378. return $array;
  379. }
  380. /**
  381. * Recursively merge two or more arrays. Values in an associative array
  382. * overwrite previous values with the same key. Values in an indexed array
  383. * are appended, but only when they do not already exist in the result.
  384. *
  385. * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
  386. *
  387. * $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
  388. * $mary = array('name' => 'mary', 'children' => array('jane'));
  389. *
  390. * // John and Mary are married, merge them together
  391. * $john = Arr::merge($john, $mary);
  392. *
  393. * // The output of $john will now be:
  394. * array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
  395. *
  396. * @param array $array1 initial array
  397. * @param array $array2,... array to merge
  398. * @return array
  399. */
  400. public static function merge($array1, $array2)
  401. {
  402. if (Arr::is_assoc($array2))
  403. {
  404. foreach ($array2 as $key => $value)
  405. {
  406. if (is_array($value)
  407. AND isset($array1[$key])
  408. AND is_array($array1[$key])
  409. )
  410. {
  411. $array1[$key] = Arr::merge($array1[$key], $value);
  412. }
  413. else
  414. {
  415. $array1[$key] = $value;
  416. }
  417. }
  418. }
  419. else
  420. {
  421. foreach ($array2 as $value)
  422. {
  423. if ( ! in_array($value, $array1, TRUE))
  424. {
  425. $array1[] = $value;
  426. }
  427. }
  428. }
  429. if (func_num_args() > 2)
  430. {
  431. foreach (array_slice(func_get_args(), 2) as $array2)
  432. {
  433. if (Arr::is_assoc($array2))
  434. {
  435. foreach ($array2 as $key => $value)
  436. {
  437. if (is_array($value)
  438. AND isset($array1[$key])
  439. AND is_array($array1[$key])
  440. )
  441. {
  442. $array1[$key] = Arr::merge($array1[$key], $value);
  443. }
  444. else
  445. {
  446. $array1[$key] = $value;
  447. }
  448. }
  449. }
  450. else
  451. {
  452. foreach ($array2 as $value)
  453. {
  454. if ( ! in_array($value, $array1, TRUE))
  455. {
  456. $array1[] = $value;
  457. }
  458. }
  459. }
  460. }
  461. }
  462. return $array1;
  463. }
  464. /**
  465. * Overwrites an array with values from input arrays.
  466. * Keys that do not exist in the first array will not be added!
  467. *
  468. * $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
  469. * $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
  470. *
  471. * // Overwrite the values of $a1 with $a2
  472. * $array = Arr::overwrite($a1, $a2);
  473. *
  474. * // The output of $array will now be:
  475. * array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
  476. *
  477. * @param array $array1 master array
  478. * @param array $array2 input arrays that will overwrite existing values
  479. * @return array
  480. */
  481. public static function overwrite($array1, $array2)
  482. {
  483. foreach (array_intersect_key($array2, $array1) as $key => $value)
  484. {
  485. $array1[$key] = $value;
  486. }
  487. if (func_num_args() > 2)
  488. {
  489. foreach (array_slice(func_get_args(), 2) as $array2)
  490. {
  491. foreach (array_intersect_key($array2, $array1) as $key => $value)
  492. {
  493. $array1[$key] = $value;
  494. }
  495. }
  496. }
  497. return $array1;
  498. }
  499. /**
  500. * Creates a callable function and parameter list from a string representation.
  501. * Note that this function does not validate the callback string.
  502. *
  503. * // Get the callback function and parameters
  504. * list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
  505. *
  506. * // Get the result of the callback
  507. * $result = call_user_func_array($func, $params);
  508. *
  509. * @param string $str callback string
  510. * @return array function, params
  511. */
  512. public static function callback($str)
  513. {
  514. // Overloaded as parts are found
  515. $command = $params = NULL;
  516. // command[param,param]
  517. if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
  518. {
  519. // command
  520. $command = $match[1];
  521. if ($match[2] !== '')
  522. {
  523. // param,param
  524. $params = preg_split('/(?<!\\\\),/', $match[2]);
  525. $params = str_replace('\,', ',', $params);
  526. }
  527. }
  528. else
  529. {
  530. // command
  531. $command = $str;
  532. }
  533. if (strpos($command, '::') !== FALSE)
  534. {
  535. // Create a static method callable command
  536. $command = explode('::', $command, 2);
  537. }
  538. return [$command, $params];
  539. }
  540. /**
  541. * Convert a multi-dimensional array into a single-dimensional array.
  542. *
  543. * $array = array('set' => array('one' => 'something'), 'two' => 'other');
  544. *
  545. * // Flatten the array
  546. * $array = Arr::flatten($array);
  547. *
  548. * // The array will now be
  549. * array('one' => 'something', 'two' => 'other');
  550. *
  551. * [!!] The keys of array values will be discarded.
  552. *
  553. * @param array $array array to flatten
  554. * @return array
  555. * @since 3.0.6
  556. */
  557. public static function flatten($array)
  558. {
  559. $is_assoc = Arr::is_assoc($array);
  560. $flat = [];
  561. foreach ($array as $key => $value)
  562. {
  563. if (is_array($value))
  564. {
  565. $flat = array_merge($flat, Arr::flatten($value));
  566. }
  567. else
  568. {
  569. if ($is_assoc)
  570. {
  571. $flat[$key] = $value;
  572. }
  573. else
  574. {
  575. $flat[] = $value;
  576. }
  577. }
  578. }
  579. return $flat;
  580. }
  581. }