6

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;
        }
    }   
}
5
  • And what you have tried so far? Post your attempts too Commented Aug 5, 2015 at 6:28
  • @Uchiha - i edited the Question. And Updated My code here Commented Aug 5, 2015 at 6:35
  • use for_each with $array_key since explode returns an array Commented Aug 5, 2015 at 6:54
  • @phplover Unable to understand your comment Commented Aug 5, 2015 at 6:54
  • Inverse task: PHP - Convert multidimensional array to 2D array with dot notation keys Commented Mar 19 at 9:47

1 Answer 1

1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.