需要一些帮助制作一个PHP搜索树

时间:2015-06-23 03:31:45

标签: php tree

我正在制作一个树来存储php中的单词和相关的数字数组。我需要它看起来像这样: 单词:apple,ant

[a] => Array
    (
        [p] => Array
            (
                [p] => Array
                    (
                        [l] => Array
                            (
                                [e] => Array
                                    (
                                        [0] => Array
                                            (
                                                [0] => 0
                                                [1] => 0
                                                [2] => 1
                                                [3] => 2
                                                [4] => 3
                                                [5] => 4
                                            )

                                    )

                            )

                    )

            )

        [n] => Array
            (
                [t] => Array
                    (
                        [0] => Array
                            (
                                [0] => 0
                                [1] => 1
                                [2] => 2
                                [3] => 0
                                [4] => 0
                                [5] => 4
                             )

                    )

           )

    )

苹果和蚂蚁当然需要共享相同的[a]索引。我很接近,但我无法弄清楚如何正确地跟踪树索引,所以' apple'进入树很好但是' ant'插入为' nt'。现在是我的代码:

private function insertWordsIntoTree()
{
    foreach ($this->words as $word)
    {
        $characters = preg_replace('/[0-9]+/', '', $words);

        $points = $this->getPoints($word);

        $this->tree = $this->buildTree($characters, $points, $this->tree);
    }

    print_r($this->tree);
}

private function buildTree($characters, array $points, array $tree)
{
    for ($i = 0; $i < strlen($characters); $i++) 
    {
        $character = $characters[$i];

        $remaining_characters = substr($characters, $i + 1);

        if (strlen($characters) === 1)
        {
            $child = [];

            $child[$character] = [$points];

            return $child;
        }
        elseif (!isset($tree[$character])) 
        {
            $tree[$character] = $this->buildTree($remaining_characters, $points, []);;

            break;
        }
        else
        {
            $this->buildTree($remaining_characters, $points, $tree[$character]);
        }
    }

    return $tree;
}

我很确定问题出在else语句中......我不认为我正确地跟踪当前的树索引。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是一种将递归传递给php的简单方法:

$tree = array();
foreach($words as $word) {
    $characters = array_reverse(str_split($word));
    $temp = array();
    foreach($characters as $index => $character) {
        if($index == 0) {
            $temp[] = getPoints($word);
        }
        $temp = array(
            $character => $temp
        );
    }
    $tree = array_merge_recursive($tree, $temp);
}