Convert array key to multidimensional array

I have an array as shown 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 as 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 an explosion. it works if the entire key has only one ".". But the key is dynamic. so please help me convert the array dynamically. I tried this code below

 $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; } } } 
+7
arrays php multidimensional-array
source share
1 answer

There may be more elegant ways to get around this, but here is one example of this with a 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); } 
+1
source share

All Articles