Last active
December 31, 2015 21:39
-
-
Save saulopaiva/8048348 to your computer and use it in GitHub Desktop.
Function for flatten array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <? | |
| /** | |
| Transforms: | |
| $data = array( | |
| 'user' => array( | |
| 'email' => '[email protected]', | |
| 'name' => 'Super User', | |
| 'address' => array( | |
| 'billing' => 'Street 1', | |
| 'delivery' => 'Street 2' | |
| ) | |
| ), | |
| 'post' => 'Hello, World!' | |
| ); | |
| Into: | |
| Array | |
| ( | |
| [user.email] => [email protected] | |
| [user.name] => Super User | |
| [user.address.billing] => Street 1 | |
| [user.address.delivery] => Street 2 | |
| [post] => Hello, World! | |
| ) | |
| */ | |
| function flatten($array, $prefix = '', $glue = '.') { | |
| $result = array(); | |
| foreach($array as $key=>$value) { | |
| if(is_array($value)) { | |
| $result = $result + flatten($value, $prefix . $key . $glue); | |
| } | |
| else { | |
| $result[$prefix.$key] = $value; | |
| } | |
| } | |
| return $result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment