File tree Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -73,6 +73,7 @@ Dot has the following methods:
7373- [ clear()] ( #clear )
7474- [ count()] ( #count )
7575- [ delete()] ( #delete )
76+ - [ flatten()] ( #flatten )
7677- [ get()] ( #get )
7778- [ has()] ( #has )
7879- [ isEmpty()] ( #isEmpty )
@@ -175,6 +176,14 @@ $dot->delete([
175176]);
176177```
177178
179+ <a name =" flatten " ></a >
180+ ### flatten()
181+
182+ Returns a flattened array with the keys delimited by a given character (default "."):
183+ ``` php
184+ $flatten = $dot->flatten();
185+ ```
186+
178187<a name =" get " ></a >
179188### get()
180189
Original file line number Diff line number Diff line change @@ -132,6 +132,36 @@ protected function exists($array, $key)
132132 return array_key_exists ($ key , $ array );
133133 }
134134
135+ /**
136+ * Flatten an array with the given character as a key delimiter
137+ *
138+ * @param string $delimiter
139+ * @param array|null $items
140+ * @param string $prepend
141+ * @return array
142+ */
143+ public function flatten ($ delimiter = '. ' , $ items = null , $ prepend = '' )
144+ {
145+ $ flatten = [];
146+
147+ if (is_null ($ items )) {
148+ $ items = $ this ->items ;
149+ }
150+
151+ foreach ($ items as $ key => $ value ) {
152+ if (is_array ($ value ) && !empty ($ value )) {
153+ $ flatten = array_merge (
154+ $ flatten ,
155+ $ this ->flatten ($ delimiter , $ value , $ prepend .$ key .$ delimiter )
156+ );
157+ } else {
158+ $ flatten [$ prepend .$ key ] = $ value ;
159+ }
160+ }
161+
162+ return $ flatten ;
163+ }
164+
135165 /**
136166 * Return the value of a given key
137167 *
Original file line number Diff line number Diff line change @@ -170,6 +170,27 @@ public function testDeleteArrayOfKeys()
170170 $ this ->assertSame ([], $ dot ->all ());
171171 }
172172
173+ /*
174+ * --------------------------------------------------------------
175+ * Flatten
176+ * --------------------------------------------------------------
177+ */
178+ public function testFlatten ()
179+ {
180+ $ dot = new Dot (['foo ' => ['abc ' => 'xyz ' , 'bar ' => ['baz ' ]]]);
181+ $ flatten = $ dot ->flatten ();
182+ $ this ->assertEquals ('xyz ' , $ flatten ['foo.abc ' ]);
183+ $ this ->assertEquals ('baz ' , $ flatten ['foo.bar.0 ' ]);
184+ }
185+
186+ public function testFlattenWithCustomDelimiter ()
187+ {
188+ $ dot = new Dot (['foo ' => ['abc ' => 'xyz ' , 'bar ' => ['baz ' ]]]);
189+ $ flatten = $ dot ->flatten ('_ ' );
190+ $ this ->assertEquals ('xyz ' , $ flatten ['foo_abc ' ]);
191+ $ this ->assertEquals ('baz ' , $ flatten ['foo_bar_0 ' ]);
192+ }
193+
173194 /*
174195 * --------------------------------------------------------------
175196 * Get
You can’t perform that action at this time.
0 commit comments