Last active
July 6, 2023 18:04
-
-
Save wgrafael/8a9bb1a963042bc88dac to your computer and use it in GitHub Desktop.
Convert array with key in dot notation for multidimensional 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
| <?php | |
| /** | |
| * Convert array with key in dot notation for multidimensional array | |
| * | |
| * Example: | |
| * Input: [ "name.firstname" => "Rafael", "name.lastname" => "Dantas", "a.b.c" => "d" ] | |
| * Output: [ "name" => [ "firstname" => "Rafael", "lastname" => "Dantas" ], "a" => [ "b" => [ "c" => "d" ] ] | |
| * | |
| * @param $array Array with key in dot notation | |
| * @return Array array multidimensional | |
| * @author Rafael Dantas | |
| */ | |
| function convertDotToArray($array) { | |
| $newArray = array(); | |
| foreach($array as $key => $value) { | |
| $dots = explode(".", $key); | |
| if(count($dots) > 1) { | |
| $last = &$newArray[ $dots[0] ]; | |
| foreach($dots as $k => $dot) { | |
| if($k == 0) continue; | |
| $last = &$last[$dot]; | |
| } | |
| $last = $value; | |
| } else { | |
| $newArray[$key] = $value; | |
| } | |
| } | |
| return $newArray; | |
| } |
This is not exact, but is realted. Here are simple getter and setter functions to allow using a single string, dot notation path for accessing multidimensional properties in PHP. E.g. "prop1.prop2.prop3"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obrigado por compartilhar essa solução.
Fiz um aprimoramento: