2

I have a string like this:

a,,b,c,,d,,,e,f,g,,e,,,,

I would like to get an array like this:

Array
(
    [a] => Array
        (
        )

    [b] => Array
        (
            [c] => Array
                (
                )

            [d] => Array
                (
                )

        )

    [e] => Array
        (
            [f] => Array
                (
                    [g] => Array
                        (
                        )

                    [e] => Array
                        (
                        )

                )

        )

)

The logic is: After an item the first comma opens the item, the second one will close the item, everything between the two commas are its children.

I made this function:

function source() {
    global $get;
    $items = array();
    $item = true;
    while ($item) {
        $pieces = explode(',', $get, 2);
        if (!empty($pieces[1])) $get = $pieces[1];
        $item = $pieces[0];
        if ($item) $items[$item] = source();
    }
    return $items;
}
$get = 'a,,b,c,,d,,,e,f,g,,e,,,,';
print_r (source());

I still got some issues, like if the string finishes with item plus a comma or with no comma I get an endless loop. I know I can check if there are enough commas and add them before calling the function, but I don't like my function. I know someone is better then me on this. So I'm asking:

What can be the best solution to convert a string(tree, separated only with commas) into an multidimensional array()?

p.s. I'm not sure if this is the best way of asking.

1 Answer 1

3
function parse_tree($str) {
    $base_arr = array();
    $arr = &$base_arr;
    $stack = array();
    foreach (explode(',', $str) as $char) {
        if ($char !== '') {
            $arr[$char] = array();
            $stack[] = &$arr;
            $arr = &$arr[$char];
        } elseif ($stack && $char === '') {
            $tmp = array_slice($stack, -1, 1);
            $arr = &$tmp[0];
            array_pop($stack);
        }
    }
    return $base_arr;
}

Worked fine on Codepad: http://codepad.org/PwKFfQfD

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.