0

I have a set of strings that are formatted like "A.B.C" and can have varying 'depths'. I.E. one might be just "A" or could be "A.B.C.D".

I want to be able to convert it into the keys for an associative array. So "A" would translate to

$var["A"] = $val;

And "A.B" would translate to

$var["A"]["B"] = $val;
3
  • 5
    Cool story bro. What did you try? Commented Sep 30, 2013 at 20:10
  • I've seen several people doing similar things with fixed depth keys by using explode (stackoverflow.com/questions/6406462/…). I, however, don't know the depth of the array in advance. Commented Sep 30, 2013 at 20:12
  • possible duplicate of Access multidimensional array by string with delimiter - this is only one of the many duplicates. Please be a little more creative how to search for :) Commented Sep 30, 2013 at 20:36

2 Answers 2

1

Using a recursive function and passing by &reference

$str = "A.B.C" ;

$letters = explode(".", $str);

$result = array() ;

function goDeep(&$array, $letters, $level){
  if ($level >= count($letters)){
    $array = "Your value here" ;
    return ;
  }

  $array[$letters[$level]] = array() ;
  goDeep($array[$letters[$level]], $letters, ++$level);
}

goDeep($result, $letters, 0);
var_dump($result);                 //3 - level deep array is ready.
Sign up to request clarification or add additional context in comments.

1 Comment

I had to remove the initialization of "$array[$letters[$level]] = array();" to work with multiple passes, but thank you.
0

Solution can be eval().

<?php
    $a = "A.B.C";
    $temp = explode('.',$a);
    $keys = "";
    foreach ($temp as $value) {
        $keys .= "['$value']";
    }
    $val = "XXX";
    $var = array();
    eval('$var'.$keys.' = $val;');
    print_r($var);
?>

Result like :

Array ( [A] => Array ( [B] => Array ( [C] => XXX ) ) )

5 Comments

$var is an empty array. Indeces A, B will be undefined.
Did you run it ? I ran and got this result Array ( [A] => Array ( [B] => Array ( [C] => XXX ) ) ) . So,Indeces A,B cannot be undefined after run the eval code.
I kinda have no idea why it works :D
What about the usual warning that eval is evil? Especially if the string comes from user input!
Yes, eval is dangerous function to use. If you don't know anything about validation , you shouldn't use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.