简体   繁体   English

字符串,仅用逗号分隔到多维php数组的树

[英]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. 我仍然遇到一些问题,例如,如果字符串以item加一个逗号结束或没有逗号结束,则会出现一个无限循环。 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()? 将字符串(树,仅用逗号分隔)转换为多维array()的最佳解决方案是什么?

ps I'm not sure if this is the best way of asking. ps我不确定这是否是最好的询问方式。

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 在Codepad上工作正常: http//codepad.org/PwKFfQfD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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