arr.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php namespace Laravel;
  2. class Arr {
  3. /**
  4. * Get an item from an array.
  5. *
  6. * If the specified key is null, the entire array will be returned. The array may
  7. * also be accessed using JavaScript "dot" style notation. Retrieving items nested
  8. * in multiple arrays is also supported.
  9. *
  10. * <code>
  11. * // Returns "taylor"
  12. * Arr::get(array('name' => array('is' => 'Taylor')), 'name.is');
  13. * </code>
  14. *
  15. * @param array $array
  16. * @param string $key
  17. * @param mixed $default
  18. * @return mixed
  19. */
  20. public static function get($array, $key, $default = null)
  21. {
  22. if (is_null($key)) return $array;
  23. foreach (explode('.', $key) as $segment)
  24. {
  25. if ( ! is_array($array) or ! array_key_exists($segment, $array))
  26. {
  27. return is_callable($default) ? call_user_func($default) : $default;
  28. }
  29. $array = $array[$segment];
  30. }
  31. return $array;
  32. }
  33. /**
  34. * Set an array item to a given value.
  35. *
  36. * This method is primarly helpful for setting the value in an array with
  37. * a variable depth, such as configuration arrays.
  38. *
  39. * If the specified item doesn't exist, it will be created. If the item's
  40. * parents do no exist, they will also be created as arrays.
  41. *
  42. * Like the Arr::get method, JavaScript "dot" syntax is supported.
  43. *
  44. * <code>
  45. * // Set "name.is" to "taylor"
  46. * Arr::set(array('name' => array('is' => 'something')), 'name.is', 'taylor');
  47. * </code>
  48. *
  49. * @param array $array
  50. * @param string $key
  51. * @param mixed $value
  52. * @return void
  53. */
  54. public static function set(&$array, $key, $value)
  55. {
  56. if (is_null($key)) return $array = $value;
  57. $keys = explode('.', $key);
  58. while (count($keys) > 1)
  59. {
  60. $key = array_shift($keys);
  61. if ( ! isset($array[$key]) or ! is_array($array[$key]))
  62. {
  63. $array[$key] = array();
  64. }
  65. $array =& $array[$key];
  66. }
  67. $array[array_shift($keys)] = $value;
  68. }
  69. }