简体   繁体   中英

String, tree separated only with commas to an multidimensional php array

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()?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM