如何从PHP数组创建层次结果的递归函数?

时间:2014-01-31 08:59:45

标签: php mysql

我在“test_group”表中有以下记录,我从SELECT查询得到了数组结果。

group_id    group_name      parent_id
1           fruits          0
2           vegetables      0
3           one seed        1
4           many seed       1
5           seedless        2
6           many seed       2
7           mango           3
8           guava           4
9           jack fruit      4
10          gooseberry      3
11          drumstick       6
12          beans           6
13          onion           5
14          cauli flower    5

查询:

SELECT * FROM test_groups;

结果:

Array (
    [0] => Array
        (
            [group_id] => 1
            [group_name] => fruits
            [parent_id] => 0
        )
    [1] => Array
        (
            [group_id] => 2
            [group_name] => vegetables
            [parent_id] => 0
        )
    [2] => Array
        (
            [group_id] => 3
            [group_name] => one seed
            [parent_id] => 1
        )
    [3] => Array
        (
            [group_id] => 4
            [group_name] => many seed
            [parent_id] => 1
        )
    [4] => Array
        (
            [group_id] => 5
            [group_name] => seedless
            [parent_id] => 2
        )
    [5] => Array
        (
            [group_id] => 6
            [group_name] => many seed
            [parent_id] => 2
        )
    [6] => Array
        (
            [group_id] => 7
            [group_name] => mango
            [parent_id] => 3
        )
    [7] => Array
        (
            [group_id] => 8
            [group_name] => guava
            [parent_id] => 4
        )
    [8] => Array
        (
            [group_id] => 9
            [group_name] => jack fruit
            [parent_id] => 4
        )
    [9] => Array
        (
            [group_id] => 10
            [group_name] => gooseberry
            [parent_id] => 3
        )
    [10] => Array
        (
            [group_id] => 11
            [group_name] => drumstick
            [parent_id] => 6
        )
    [11] => Array
        (
            [group_id] => 12
            [group_name] => beans
            [parent_id] => 6
        )
    [12] => Array
        (
            [group_id] => 13
            [group_name] => onion
            [parent_id] => 5
        )
    [13] => Array
        (
            [group_id] => 14
            [group_name] => cauli flower
            [parent_id] => 5
        )

)

我想从这些结果中得到以下输出。如何使用这些结果集来构建层次结构级别?请帮助我,谢谢你的进步。

<ul>
<li>Fruits</li>
    <ul>
        <li>one seed</li>
        <ul>
            <li>mango</li>
            <li>gooseberry</li>
        </ul>
        <li>many seed</li>
        <ul>
            <li>guava</li>
            <li>jack fruit</li>
        </ul>
    </ul>
<li>Vegetables</li>
    <ul>
        <li>seedless</li>
        <ul>
            <li>onion</li>
            <li>cauli flower</li>
        </ul>
        <li>many seed</li>
        <ul>
            <li>drumstick</li>
            <li>beans</li>
        </ul>
    </ul>
</ul>

3 个答案:

答案 0 :(得分:3)

您可以使用递归或不使用来构建列表:

使用递归:

function array_to_tree_recursive(array $array, $parent_id = 0)
{
    $return = array();

    foreach ($array as $k => $v) {
        if ($v['parent_id'] == $parent_id) {
            $return[$k] = $v; 
            $return[$k]['children'] = array_to_tree_recursive($array, $v['group_id']);  
        }
    }

    return $return;
}

没有递归:

function array_to_tree(array $array, $parent_id = 0)
{
    $array = array_combine(array_column($array, 'group_id'), array_values($array));

    foreach ($array as $k => &$v) {
        if (isset($array[$v['parent_id']])) {
            $array[$v['parent_id']]['children'][$k] = &$v;
        }
        unset($v);
    }

    return array_filter($array, function($v) use ($parent_id) {
        return $v['parent_id'] == $parent_id;
    });
}

将树转换为列表:

function tree_to_list(array $tree) {
    $return = "";

    foreach ($tree as $branch) {
        $return .= "\n<li>".$branch['group_name']."</li>";
        if (isset($branch['children']) && sizeof($branch['children'])) {
            $return .= tree_to_list($branch['children']);
        }
    }

    return "\n<ul>{$return}</ul>\n";
}

用法:

echo tree_to_list(array_to_tree($a));

输出:

<ul>
<li>fruits</li>
<ul>
<li>one seed</li>
<ul>
<li>mango</li>
<li>gooseberry</li></ul>

<li>many seed</li>
<ul>
<li>guava</li>
<li>jack fruit</li></ul>
</ul>

<li>vegetables</li>
<ul>
<li>seedless</li>
<ul>
<li>onion</li>
<li>cauli flower</li></ul>

<li>many seed</li>
<ul>
<li>drumstick</li>
<li>beans</li></ul>
</ul>
</ul>

答案 1 :(得分:1)

首先,我们创建一些基本的树管理功能:

/* in a separate file for your custom functions: */
function createTreeFromList($list) {
    $tree = array();
    foreach($list AS $item) {
        if(isset($tree[$item['group_id']])) {
            array_merge($tree[$item['group_id']], $item);
        }
        else {
            $tree[$item['group_id']] = $item;
        }
        if(!isset($tree[$item['parent_id']]) {
            $tree[$item['parent_id']] = array();
            $tree[$item['parent_id']]['children'] = array();
        }
        $tree[$item['parent_id']]['children'] []= &$item;
    }
    return($tree);
}

function printTree($tree) {
    echo("<ul>");
    foreach($tree AS $node) {
        echo("<li>".$node['group_name']."</li>");
        if(!empty($node['children'])) {
            echo("<li>");
            printTree($node['children']);
            echo("</li>");
        }
    }
    echo("</ul>");
}

我们使用它们:

/* in our current file */

/* gain access to the functions we've defined */
include('path/to/our/functions_file.php');

/* select all rows in the tree: */
$sql = "SELECT * ...";
$rows = $pdo->query($sql)->fetchAll();

/* iterate over the list in order to create an equivalent tree: */
$tree = createTreeFromList($rows);

/* Then we print the tree: */
printTree($tree);

答案 2 :(得分:0)

$result = query;
for($i=0 to end)
    find_child($i); 


function find_child($gid){
    echo "<ul>";
    for($i=0 to end){
        if($result[$i].parent_id == gid){
            echo "<li>"+$result+"</li>"
            find_child($result[i].group_id);
        }
    }
    echo "</ul>";
}