diff --git a/README.md b/README.md index d03e464..2157a32 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ Dot has the following methods: - [clear()](#clear) - [count()](#count) - [delete()](#delete) +- [flatten()](#flatten) - [get()](#get) - [has()](#has) - [isEmpty()](#isEmpty) @@ -175,6 +176,14 @@ $dot->delete([ ]); ``` + +### flatten() + +Returns a flattened array with the keys delimited by a given character (default "."): +```php +$flatten = $dot->flatten(); +``` + ### get() diff --git a/src/Dot.php b/src/Dot.php index 83bf7b5..0a61665 100644 --- a/src/Dot.php +++ b/src/Dot.php @@ -132,6 +132,36 @@ protected function exists($array, $key) return array_key_exists($key, $array); } + /** + * Flatten an array with the given character as a key delimiter + * + * @param string $delimiter + * @param array|null $items + * @param string $prepend + * @return array + */ + public function flatten($delimiter = '.', $items = null, $prepend = '') + { + $flatten = []; + + if (is_null($items)) { + $items = $this->items; + } + + foreach ($items as $key => $value) { + if (is_array($value) && !empty($value)) { + $flatten = array_merge( + $flatten, + $this->flatten($delimiter, $value, $prepend.$key.$delimiter) + ); + } else { + $flatten[$prepend.$key] = $value; + } + } + + return $flatten; + } + /** * Return the value of a given key * diff --git a/tests/DotTest.php b/tests/DotTest.php index 1e1c138..2c90174 100644 --- a/tests/DotTest.php +++ b/tests/DotTest.php @@ -170,6 +170,27 @@ public function testDeleteArrayOfKeys() $this->assertSame([], $dot->all()); } + /* + * -------------------------------------------------------------- + * Flatten + * -------------------------------------------------------------- + */ + public function testFlatten() + { + $dot = new Dot(['foo' => ['abc' => 'xyz', 'bar' => ['baz']]]); + $flatten = $dot->flatten(); + $this->assertEquals('xyz', $flatten['foo.abc']); + $this->assertEquals('baz', $flatten['foo.bar.0']); + } + + public function testFlattenWithCustomDelimiter() + { + $dot = new Dot(['foo' => ['abc' => 'xyz', 'bar' => ['baz']]]); + $flatten = $dot->flatten('_'); + $this->assertEquals('xyz', $flatten['foo_abc']); + $this->assertEquals('baz', $flatten['foo_bar_0']); + } + /* * -------------------------------------------------------------- * Get