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;
}
@newpoow
Copy link

newpoow commented Sep 24, 2018

Obrigado por compartilhar essa solução.
Fiz um aprimoramento:

protected function normalizeArray(array $items, $delimiter = '.')
    {
        $new = array();
        foreach ($items as $key => $value) {
            if (strpos($key, $delimiter) === false) {
                $new[$key] = is_array($value) ? $this->normalizeArray($value, $delimiter) : $value;
                continue;
            }

            $segments = explode($delimiter, $key);
            $last = &$new[$segments[0]];
            if (!is_null($last) && !is_array($last)) {
                throw new \LogicException(sprintf("The '%s' key has already been defined as being '%s'", $segments[0], gettype($last)));
            }

            foreach ($segments as $k => $segment) {
                if ($k != 0) {
                    $last = &$last[$segment];
                }
            }
            $last = is_array($value) ? $this->normalizeArray($value, $delimiter) : $value;
        }
        return $new;
    }

@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