0

Having a generic string $a and exploding it for dot es:

$b = explode(".", $a)

How i can to Runtime code it dinamically without to know count($b) value:

if (count($b) == 1) {
    $c[$b[0]] = $var;
} elseif (count($b) == 2) {
    $c[$b[0]][$b[1]] = $var;
} elseif (count($b) == 3) {
    $c[$b[0]][$b[1]][$b[2]] = $var;
} ... {
    ...
} elseif (count($b) == n-1) {
    $c[$b[0]][$b[1]][$b[2]]...[$b[n-2]] = $var;
} elseif (count($b) == n) {
     $c[$b[0]][$b[1]][$b[2]]...[$b[n-1]] = $var;
} else {
     $c = $var;
}

It is a pseudocode ofcourse for give an idea about what i mean.

2
  • 2
    Could you please add an example string and the expected output? And have you actually tried anything yourself, or are you asking us to do all the work for you? Commented Dec 25, 2016 at 13:31
  • Can you post $a string Commented Dec 25, 2016 at 13:31

2 Answers 2

2

Solution without eval() and recursion:

function split_to_multi($string, $value)
{
    $levels = explode('.', $string);
    $result = [];
    foreach (array_reverse($levels) as $key) {
        $result = [$key => $value];
        $value = $result;
    }

    return $result;
}

For example:

print_r(split_to_multi('foo.bar.baz', 123)); 

Will output:

Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [baz] => 123
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

2

You have two solutions:

Recursive function

The first is using a recursive function that will add each new element on the array.

Evaluation method

Another method, very quick ... but it's using an evaluation function. I'm not a big fan of such. Use it when you know all sides effect on your script.

php convert flat family list to tree

function arrayToTree_eval(array $source, $defaultValue = null) {

    eval(sprintf('$tree%s = $defaultValue;', '["' . implode('"]["', $values) . '"]'));
    // will create a $tree['a']['b']['...'] = $defaultValue

    return $tree;
}

var_dump( arrayToTree_eval( explode('.', 'a.b.c.d') ) );

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.