Search code examples
phparraysmultidimensional-arraydot-notation

Convert flat array with dot-delimited keys to nested array


I am trying to created nested array from flat based on its keys. Also format of keys in original array can be changed if it will simplify task.

From :

$arr = [
        'player.name' => 'Joe',
        'player.lastName' => 'Snow',
        'team.name' => 'Stars',
        'team.picture.name' => 'Joe Snow Profile',
        'team.picture.file' => 'xxx.jpg'
    ];

To:

$arr = [
        'player' => [
            'name' => 'Joe'
            , 'lastName' => 'Snow'
        ]
        ,'team' => [
            'name'=> 'Stars'
            ,'picture' => [
                'name' => 'Joe Snow Profile'
                , 'file' =>'xxx.jpg'
            ]
        ],
    ];

Solution

  • Here is my take on it.
    It should be able to handle arbitrary depth

    function unflatten($arr) {
        $result = array();
    
        foreach($arr as $key => $value) {
            $keys = explode(".", $key); //potentially other separator
            $lastKey = array_pop($keys);
    
            $node = &$result;
            foreach($keys as $k) {
                if (!array_key_exists($k, $node))
                    $node[$k] = array();
                $node = &$node[$k];
            }
    
            $node[$lastKey] = $value;
        }
    
        return $result;
    }