Files
spa-api/system/arr.php

68 lines
1.4 KiB
PHP
Raw Normal View History

<?php namespace System;
class Arr {
/**
* Get an item from an array.
*
* If the specified key is null, the entire array will be returned. The array may
2011-08-09 14:31:57 -05:00
* also be accessed using JavaScript "dot" style notation. Retrieving items nested
* in multiple arrays is also supported.
*
* @param array $array
2011-06-16 22:27:57 -05:00
* @param string $key
* @param mixed $default
* @return mixed
*/
2011-06-16 22:27:57 -05:00
public static function get($array, $key, $default = null)
{
2011-08-08 08:27:12 -05:00
if (is_null($key)) return $array;
2011-08-02 13:38:50 -05:00
foreach (explode('.', $key) as $segment)
{
2011-08-15 15:05:57 -05:00
if ( ! is_array($array) or ! array_key_exists($segment, $array))
2011-08-02 13:38:50 -05:00
{
return is_callable($default) ? call_user_func($default) : $default;
}
$array = $array[$segment];
}
return $array;
}
2011-08-15 00:16:37 -05:00
/**
2011-08-15 10:38:02 -05:00
* Set an array item to a given value.
2011-08-15 00:16:37 -05:00
*
* This method is primarly helpful for setting the value in an array with
2011-08-15 00:20:43 -05:00
* a variable depth, such as configuration arrays.
2011-08-15 00:16:37 -05:00
*
* Like the Arr::get method, JavaScript "dot" syntax is supported.
*
* @param array $array
* @param string $key
* @param mixed $value
* @return void
*/
public static function set(&$array, $key, $value)
{
if (is_null($key)) return $array = $value;
$keys = explode('.', $key);
2011-08-15 00:16:37 -05:00
while (count($keys) > 1)
2011-08-15 00:16:37 -05:00
{
$key = array_shift($keys);
2011-08-15 15:05:57 -05:00
if ( ! isset($array[$key]) or ! is_array($array[$key]))
2011-08-15 00:16:37 -05:00
{
$array[$key] = array();
2011-08-15 00:16:37 -05:00
}
$array =& $array[$key];
2011-08-15 00:16:37 -05:00
}
$array[array_shift($keys)] = $value;
2011-08-15 00:16:37 -05:00
}
}