Skip to content

Commit

Permalink
Merge pull request #5 from XAKEPEHOK/2.x
Browse files Browse the repository at this point in the history
Add method Dot::flatten() which returns a flattened array
  • Loading branch information
adbario authored Jul 22, 2018
2 parents 90c0b7d + 9913260 commit 895fe4b
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Dot has the following methods:
- [clear()](#clear)
- [count()](#count)
- [delete()](#delete)
- [flatten()](#flatten)
- [get()](#get)
- [has()](#has)
- [isEmpty()](#isEmpty)
Expand Down Expand Up @@ -175,6 +176,14 @@ $dot->delete([
]);
```

<a name="flatten"></a>
### flatten()

Returns a flattened array with the keys delimited by a given character (default "."):
```php
$flatten = $dot->flatten();
```

<a name="get"></a>
### get()

Expand Down
30 changes: 30 additions & 0 deletions src/Dot.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
21 changes: 21 additions & 0 deletions tests/DotTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 895fe4b

Please sign in to comment.