Skip to content
Advertisement

Flat array to nested by keys

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'
            ]
        ],
    ];

Advertisement

Answer

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;
}

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement