Skip to content

Instantly share code, notes, and snippets.

@wgrafael
Last active July 6, 2023 18:04
Show Gist options
  • Select an option

  • Save wgrafael/8a9bb1a963042bc88dac to your computer and use it in GitHub Desktop.

Select an option

Save wgrafael/8a9bb1a963042bc88dac to your computer and use it in GitHub Desktop.
Convert array with key in dot notation for multidimensional array
<?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;
}
@exoboy
Copy link

exoboy commented Jul 6, 2023

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"

https://github.com/exoboy/pathkeys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment