making deep set/get possible using dot notation
This commit is contained in:
@ -33,6 +33,11 @@ $ary['newItem']=20;
|
||||
|
||||
count($ary); //returns 3
|
||||
$ary->all(); // returns simple php array;
|
||||
|
||||
// deep assignment/retrieval
|
||||
$ary = ary(['products' => ['desk' => ['price' => 100]]]);
|
||||
$value = $ary['products.desk.price']; //100
|
||||
$ary['production.table.weight']=200;
|
||||
~~~~~~
|
||||
|
||||
|
||||
|
33
src/Ary.php
33
src/Ary.php
@ -97,7 +97,16 @@ class Ary implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
|
||||
if ($this->offsetExists($key)) {
|
||||
return $this->items[$key];
|
||||
}
|
||||
return $default;
|
||||
|
||||
$array = $this->items;
|
||||
foreach (explode('.', $key) as $segment) {
|
||||
if (!is_array($array) || !array_key_exists($segment, $array)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$array = $array[$segment];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -122,10 +131,28 @@ class Ary implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
|
||||
{
|
||||
if (is_null($key)) {
|
||||
$this->items[] = $value;
|
||||
return;
|
||||
}
|
||||
else {
|
||||
$this->items[$key] = $value;
|
||||
|
||||
// $this->items[$key] = $value;
|
||||
|
||||
$keys = explode('.', $key);
|
||||
$array =& $this->items;
|
||||
while (count($keys) > 1) {
|
||||
$key = array_shift($keys);
|
||||
|
||||
// If the key doesn't exist at this depth, we will just create an empty array
|
||||
// to hold the next value, allowing us to create the arrays to hold final
|
||||
// values at the correct depth. Then we'll keep digging into the array.
|
||||
if (!isset($array[$key]) || !is_array($array[$key])) {
|
||||
$array[$key] = [];
|
||||
}
|
||||
|
||||
$array = &$array[$key];
|
||||
}
|
||||
|
||||
$array[array_shift($keys)] = $value;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -61,6 +61,9 @@ class Test extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
$ary = new Ary();
|
||||
$this->assertEquals($ary[0], null);
|
||||
|
||||
$ary = new Ary(['x' => ['xx' => ['m' => 'xxx']]]);
|
||||
$this->assertEquals($ary->get('x.xx.m'), 'xxx');
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user