Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP替换div并生成树_Php_Html_Preg Replace Callback - Fatal编程技术网

PHP替换div并生成树

PHP替换div并生成树,php,html,preg-replace-callback,Php,Html,Preg Replace Callback,我会用div做一个HTML树。所有div都有一个左填充:5作为标准以查看树及其子类别 我从数据库中获取数据,并希望在树中排列类别。我想为每个类别创建一个单独的DIV。我从数据库中取出父ID和类别的ID。所以我必须把类别放在父类别中。我想通过preg_replace_回调提取预先存在的父DIV,然后在末尾插入子类别。不幸的是,这不符合我的意愿 Databaseoutput: Array ( [cid] => 3759 [pid] => 0 [name] => Test 1 ) A

我会用div做一个HTML树。所有div都有一个
左填充:5作为标准以查看树及其子类别

我从数据库中获取数据,并希望在树中排列类别。我想为每个类别创建一个单独的DIV。我从数据库中取出父ID和类别的ID。所以我必须把类别放在父类别中。我想通过preg_replace_回调提取预先存在的父DIV,然后在末尾插入子类别。不幸的是,这不符合我的意愿

Databaseoutput:
Array ( [cid] => 3759 [pid] => 0 [name] => Test 1 )
Array ( [cid] => 3768 [pid] => 0 [name] => Testing 2 )
Array ( [cid] => 3767 [pid] => 0 [name] => Testing 3 )
Array ( [cid] => 3761 [pid] => 0 [name] => Testing 4 )
Array ( [cid] => 3763 [pid] => 3761 [name] => Sub Testing )
Array ( [cid] => 3764 [pid] => 3761 [name] => Sub Testing 1 ) 
Array ( [cid] => 3765 [pid] => 3764 [name] => Sub-Sub Testing 2 )
Array ( [cid] => 3766 [pid] => 0 [name] => Testing 5 )
我的代码是:

$code = '<div id="cat_0"></div>';
while ($cat = $db->result()) {
    $code = preg_replace_callback('#<div id=\"cat_' . $cat['pid'] . '\">(.*)<\/div>#Uism', function($match) {
        global $cat;
        return '<div id="cat_' . $cat['pid'] . '">' . $match[1] . '<div id="cat_' . $cat['cid'] . '">' . $cat['name'] . '</div></div>';
    }, $code);
}
echo $code;
我得到的结果是:

Test 1
    Testing 2
         Testing 3
             Testing 4
                 Sub Testing
                      Sub Testing 1
                          Sub-Sub Testing 2
                              Testing 5

我希望你能帮助我

这到底是怎么回事?你能给我们看看你的当前结果吗?我得到了PID 0中的所有div,而不是正确的PID-div。我编辑了我的问题并添加了我的当前结果。
Test 1
    Testing 2
         Testing 3
             Testing 4
                 Sub Testing
                      Sub Testing 1
                          Sub-Sub Testing 2
                              Testing 5