1

I have this array:

$array['a.b.c'] = 'x';
$array['a.b.d'] = 'y';
$array['e.f'] = 'z';

what want convert to this array:

$array['a']['b']['c'] = 'x';
$array['a']['b']['d'] = 'y';
$array['e']['f'] = 'z';

is in PHP any fast way how to do it please?

Thanks O.

2
  • 1
    Foreach loop exlode key on period Commented Aug 15, 2015 at 8:36
  • Could convert it to string, rebuild, and use parse_str: $arr_str = "new['".implode("']['", explode(".", key($arr)))."']=".current($arr); parse_str($arr_str); print_r($new); See test at eval.in Commented Aug 15, 2015 at 8:45

1 Answer 1

2

Here's a way using a foreach that iterates through each key of the array, explodes it, and uses the exploded values as keys for a new array:

$result = array();

foreach($array as $key => $value) {
    $new_keys = explode('.',$key);
    $last_key = array_pop($new_keys); //remove last key from $new_keys 
    $a =& $result; //make $a and $result be the same variable

    foreach($new_keys as $new_key) {
        if(!isset($a[$new_key])) {
            $a[$new_key] = array();
        }

        $a =& $a[$new_key]; //reset $a to $a[$new_key]
    }

    $a[$last_key] = $value; //put $value in the last key
}

print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.