phparraysmultidimensional-arraydelimitedkeypaths

Converting array with dot-separated keypath keys to a multidimensional array


I have an array like below

$db_resources = array('till' => array(
 'left.btn' => 'Left button',
 'left.text' => 'Left text',
 'left.input.text' => 'Left input text',
 'left.input.checkbox' => 'Left input checkbox'        
));

I need to convert this array dynamically like below

'till' => array(
    'left' => array(
        'btn' => 'Left button',
        'text' => 'Left text',
        'input' => array(
            'text' => 'Left input text',
            'checkbox' => 'Left input checkbox'
        )
    )
  )

I tried the key with explode. it works if all the key has only one ".". But the key has dynamic one. so please hep me to convert the array dynamically. I tried this Below Code

$label_array = array();
foreach($db_resources as $keey => $db_resources2){
    if (strpos($keey,'.') !== false) {  
        $array_key = explode('.',$keey);    
        $frst_key = array_shift($array_key);
        if(count($array_key) > 1){  
            $label_array[$frst_key][implode('.',$array_key)] = $db_resources2;
            //Need to change here
        }else{
            $label_array[$frst_key][implode('.',$array_key)] = $db_resources2;
        }
    }   
}

Solution

  • There might be more elegant ways to go about it, but here is one example of doing it with recursive helper function:

        function generateNew($array, $keys, $currentIndex, $value)
        {
            if ($currentIndex == count($keys) - 1)
            {
                $array[$keys[$currentIndex]] = $value;
            }
            else
            {
                if (!isset($array[$keys[$currentIndex]]))
                {
                    $array[$keys[$currentIndex]] = array();
                }
    
                $array[$keys[$currentIndex]] = generateNew($array[$keys[$currentIndex]], $keys, $currentIndex + 1, $value);
            }
    
            return $array;
        }
    
        $result = array();
        // $temp equals your original value array here...
        foreach ($temp as $combinedKey => $value)
        {
            $result = generateNew($result, explode(".", $combinedKey), 0, $value);
        }