0

I hope the title is not too bad. I'm not an english person and this would even be hard to put in one sentece in my mothertounge...

My problem is follwing:

Iwant to build a multidimensional array from a string like so:

$string = "a-b-c";
$val = "something";

$array['a']['b']['c'] = $val;

I tried some ideas of mine and ended up with a fried brain... Hopefully you can help me! Thanks!

EDIT My approach:

 function recursion($c, $p, $v) {
        if (gettype($c) !== "array") $c = array();
        $c[$p] = $v;
        return $c;
    }

    foreach ($conf as $confLine) {
        $params = preg_split('/-/', $confLine->getParam());  //Here comes "a-b-c"
        $val = $confLine->getValue();  // The value 

        for ($i = 0; $i < count($params); $i++ ) {
            $galleryConfig = recursion($galleryConfig, $params[$i], $val);
        }
    }

IMPORTANT I don't know how long the sting will be. If its a-b or a-b-c-d-e-f

5
  • Please post your ideas you tried. Commented Feb 13, 2014 at 19:27
  • 1
    explode() on - would be a start Commented Feb 13, 2014 at 19:31
  • 1
    If you don't mind me asking, why do you need to do it this way? Commented Feb 13, 2014 at 19:31
  • Looking at the title are you suggesting that $string is actually an array, or is it a string as shown? Commented Feb 13, 2014 at 19:33
  • I agreed with @SamV. Why do you need to do this? This looks like a script with bad architecture. May be you can explain where did you get a-b-c-d strings from? May be it is easier to build an array of the string' source? Commented Feb 13, 2014 at 19:38

1 Answer 1

6
$string = "a-b-c";
$val    = "something";

foreach (array_reverse(explode('-', $string)) as $key) {
    $val = array($key => $val);
}

or

$array = array_reduce(
    array_reverse(explode('-', $string)),
    function ($val, $key) { return array($key => $val); },
    $val
);
Sign up to request clarification or add additional context in comments.

2 Comments

nice one. It's a little trickier than it appears on first sight. You beat me to it by a minute. :)
Nice function() i was looking for something like this. I hope it will fit in my program!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.