Marcello Impastato
Marcello Impastato

Reputation: 2281

How to runtime make a multidimensional array from a string.

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.

Upvotes: 0

Views: 35

Answers (2)

Timurib
Timurib

Reputation: 2743

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
                )

        )

)

Upvotes: 2

Georges O.
Georges O.

Reputation: 992

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') ) );

Upvotes: 2

Related Questions