PageRenderTime 57ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/rxwandc/system/classes/kohana/arr.php

https://bitbucket.org/i1598/caiyun_stat
PHP | 602 lines | 293 code | 52 blank | 257 comment | 32 complexity | 2fb1f30256f8eac5fd7c06c27e164e9c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * Array helper.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) 2007-2012 Kohana Team
  9. * @license http://kohanaframework.org/license
  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 (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 = array();
  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. // Split the keys by delimiter
  193. $keys = explode($delimiter, $path);
  194. // Set current $array to inner-most array path
  195. while (count($keys) > 1)
  196. {
  197. $key = array_shift($keys);
  198. if (ctype_digit($key))
  199. {
  200. // Make the key an integer
  201. $key = (int) $key;
  202. }
  203. if ( ! isset($array[$key]))
  204. {
  205. $array[$key] = array();
  206. }
  207. $array = & $array[$key];
  208. }
  209. // Set key on inner-most array
  210. $array[array_shift($keys)] = $value;
  211. }
  212. /**
  213. * Fill an array with a range of numbers.
  214. *
  215. * // Fill an array with values 5, 10, 15, 20
  216. * $values = Arr::range(5, 20);
  217. *
  218. * @param integer $step stepping
  219. * @param integer $max ending number
  220. * @return array
  221. */
  222. public static function range($step = 10, $max = 100)
  223. {
  224. if ($step < 1)
  225. return array();
  226. $array = array();
  227. for ($i = $step; $i <= $max; $i += $step)
  228. {
  229. $array[$i] = $i;
  230. }
  231. return $array;
  232. }
  233. /**
  234. * Retrieve a single key from an array. If the key does not exist in the
  235. * array, the default value will be returned instead.
  236. *
  237. * // Get the value "username" from $_POST, if it exists
  238. * $username = Arr::get($_POST, 'username');
  239. *
  240. * // Get the value "sorting" from $_GET, if it exists
  241. * $sorting = Arr::get($_GET, 'sorting');
  242. *
  243. * @param array $array array to extract from
  244. * @param string $key key name
  245. * @param mixed $default default value
  246. * @return mixed
  247. */
  248. public static function get($array, $key, $default = NULL)
  249. {
  250. return isset($array[$key]) ? $array[$key] : $default;
  251. }
  252. /**
  253. * Retrieves multiple keys from an array. If the key does not exist in the
  254. * array, the default value will be added instead.
  255. *
  256. * // Get the values "username", "password" from $_POST
  257. * $auth = Arr::extract($_POST, array('username', 'password'));
  258. *
  259. * @param array $array array to extract keys from
  260. * @param array $keys list of key names
  261. * @param mixed $default default value
  262. * @return array
  263. */
  264. public static function extract($array, array $keys, $default = NULL)
  265. {
  266. $found = array();
  267. foreach ($keys as $key)
  268. {
  269. $found[$key] = isset($array[$key]) ? $array[$key] : $default;
  270. }
  271. return $found;
  272. }
  273. /**
  274. * Retrieves muliple single-key values from a list of arrays.
  275. *
  276. * // Get all of the "id" values from a result
  277. * $ids = Arr::pluck($result, 'id');
  278. *
  279. * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
  280. *
  281. * @param array $array list of arrays to check
  282. * @param string $key key to pluck
  283. * @return array
  284. */
  285. public static function pluck($array, $key)
  286. {
  287. $values = array();
  288. foreach ($array as $row)
  289. {
  290. if (isset($row[$key]))
  291. {
  292. // Found a value in this row
  293. $values[] = $row[$key];
  294. }
  295. }
  296. return $values;
  297. }
  298. /**
  299. * Adds a value to the beginning of an associative array.
  300. *
  301. * // Add an empty value to the start of a select list
  302. * Arr::unshift($array, 'none', 'Select a value');
  303. *
  304. * @param array $array array to modify
  305. * @param string $key array key name
  306. * @param mixed $val array value
  307. * @return array
  308. */
  309. public static function unshift( array & $array, $key, $val)
  310. {
  311. $array = array_reverse($array, TRUE);
  312. $array[$key] = $val;
  313. $array = array_reverse($array, TRUE);
  314. return $array;
  315. }
  316. /**
  317. * Recursive version of [array_map](http://php.net/array_map), applies one or more
  318. * callbacks to all elements in an array, including sub-arrays.
  319. *
  320. * // Apply "strip_tags" to every element in the array
  321. * $array = Arr::map('strip_tags', $array);
  322. *
  323. * // Apply $this->filter to every element in the array
  324. * $array = Arr::map(array(array($this,'filter')), $array);
  325. *
  326. * // Apply strip_tags and $this->filter to every element
  327. * $array = Arr::map(array('strip_tags',array($this,'filter')), $array);
  328. *
  329. * [!!] Because you can pass an array of callbacks, if you wish to use an array-form callback
  330. * you must nest it in an additional array as above. Calling Arr::map(array($this,'filter'), $array)
  331. * will cause an error.
  332. * [!!] Unlike `array_map`, this method requires a callback and will only map
  333. * a single array.
  334. *
  335. * @param mixed $callbacks array of callbacks to apply to every element in the array
  336. * @param array $array array to map
  337. * @param array $keys array of keys to apply to
  338. * @return array
  339. */
  340. public static function map($callbacks, $array, $keys = NULL)
  341. {
  342. foreach ($array as $key => $val)
  343. {
  344. if (is_array($val))
  345. {
  346. $array[$key] = Arr::map($callbacks, $array[$key]);
  347. }
  348. elseif ( ! is_array($keys) or in_array($key, $keys))
  349. {
  350. if (is_array($callbacks))
  351. {
  352. foreach ($callbacks as $cb)
  353. {
  354. $array[$key] = call_user_func($cb, $array[$key]);
  355. }
  356. }
  357. else
  358. {
  359. $array[$key] = call_user_func($callbacks, $array[$key]);
  360. }
  361. }
  362. }
  363. return $array;
  364. }
  365. /**
  366. * Merges one or more arrays recursively and preserves all keys.
  367. * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
  368. *
  369. * $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
  370. * $mary = array('name' => 'mary', 'children' => array('jane'));
  371. *
  372. * // John and Mary are married, merge them together
  373. * $john = Arr::merge($john, $mary);
  374. *
  375. * // The output of $john will now be:
  376. * array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
  377. *
  378. * @param array $a1 initial array
  379. * @param array $a2,... array to merge
  380. * @return array
  381. */
  382. public static function merge(array $a1, array $a2)
  383. {
  384. $result = array();
  385. for ($i = 0, $total = func_num_args(); $i < $total; $i++)
  386. {
  387. // Get the next array
  388. $arr = func_get_arg($i);
  389. // Is the array associative?
  390. $assoc = Arr::is_assoc($arr);
  391. foreach ($arr as $key => $val)
  392. {
  393. if (isset($result[$key]))
  394. {
  395. if (is_array($val) AND is_array($result[$key]))
  396. {
  397. if (Arr::is_assoc($val))
  398. {
  399. // Associative arrays are merged recursively
  400. $result[$key] = Arr::merge($result[$key], $val);
  401. }
  402. else
  403. {
  404. // Find the values that are not already present
  405. $diff = array_diff($val, $result[$key]);
  406. // Indexed arrays are merged to prevent duplicates
  407. $result[$key] = array_merge($result[$key], $diff);
  408. }
  409. }
  410. else
  411. {
  412. if ($assoc)
  413. {
  414. // Associative values are replaced
  415. $result[$key] = $val;
  416. }
  417. elseif ( ! in_array($val, $result, TRUE))
  418. {
  419. // Indexed values are added only if they do not yet exist
  420. $result[] = $val;
  421. }
  422. }
  423. }
  424. else
  425. {
  426. // New values are added
  427. $result[$key] = $val;
  428. }
  429. }
  430. }
  431. return $result;
  432. }
  433. /**
  434. * Overwrites an array with values from input arrays.
  435. * Keys that do not exist in the first array will not be added!
  436. *
  437. * $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
  438. * $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
  439. *
  440. * // Overwrite the values of $a1 with $a2
  441. * $array = Arr::overwrite($a1, $a2);
  442. *
  443. * // The output of $array will now be:
  444. * array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
  445. *
  446. * @param array $array1 master array
  447. * @param array $array2 input arrays that will overwrite existing values
  448. * @return array
  449. */
  450. public static function overwrite($array1, $array2)
  451. {
  452. foreach (array_intersect_key($array2, $array1) as $key => $value)
  453. {
  454. $array1[$key] = $value;
  455. }
  456. if (func_num_args() > 2)
  457. {
  458. foreach (array_slice(func_get_args(), 2) as $array2)
  459. {
  460. foreach (array_intersect_key($array2, $array1) as $key => $value)
  461. {
  462. $array1[$key] = $value;
  463. }
  464. }
  465. }
  466. return $array1;
  467. }
  468. /**
  469. * Creates a callable function and parameter list from a string representation.
  470. * Note that this function does not validate the callback string.
  471. *
  472. * // Get the callback function and parameters
  473. * list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
  474. *
  475. * // Get the result of the callback
  476. * $result = call_user_func_array($func, $params);
  477. *
  478. * @param string $str callback string
  479. * @return array function, params
  480. */
  481. public static function callback($str)
  482. {
  483. // Overloaded as parts are found
  484. $command = $params = NULL;
  485. // command[param,param]
  486. if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
  487. {
  488. // command
  489. $command = $match[1];
  490. if ($match[2] !== '')
  491. {
  492. // param,param
  493. $params = preg_split('/(?<!\\\\),/', $match[2]);
  494. $params = str_replace('\,', ',', $params);
  495. }
  496. }
  497. else
  498. {
  499. // command
  500. $command = $str;
  501. }
  502. if (strpos($command, '::') !== FALSE)
  503. {
  504. // Create a static method callable command
  505. $command = explode('::', $command, 2);
  506. }
  507. return array($command, $params);
  508. }
  509. /**
  510. * Convert a multi-dimensional array into a single-dimensional array.
  511. *
  512. * $array = array('set' => array('one' => 'something'), 'two' => 'other');
  513. *
  514. * // Flatten the array
  515. * $array = Arr::flatten($array);
  516. *
  517. * // The array will now be
  518. * array('one' => 'something', 'two' => 'other');
  519. *
  520. * [!!] The keys of array values will be discarded.
  521. *
  522. * @param array $array array to flatten
  523. * @return array
  524. * @since 3.0.6
  525. */
  526. public static function flatten($array)
  527. {
  528. $is_assoc = Arr::is_assoc($array);
  529. $flat = array();
  530. foreach ($array as $key => $value)
  531. {
  532. if (is_array($value))
  533. {
  534. $flat = array_merge($flat, Arr::flatten($value));
  535. }
  536. else
  537. {
  538. if ($is_assoc)
  539. {
  540. $flat[$key] = $value;
  541. }
  542. else
  543. {
  544. $flat[] = $value;
  545. }
  546. }
  547. }
  548. return $flat;
  549. }
  550. } // End arr