php无限极分类(通用版)

1,创建数据表

CREATE TABLE `city` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` char(64) NOT NULL,

  `pid` int(11) NOT NULL DEFAULT '0',

  PRIMARY KEY (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8

2.php代码

<?php

/*

  @author:luowen

  @time:2013-12-30

  @desc:无限极分类通用版

*/

$name = @$_GET["newCity"];

$id = @$_GET['id'];

$conn = mysql_connect("localhost",'root','luowen');



print_r($_GET);



if(! $conn)

    exit(mysql_error());



mysql_query("use test",$conn);



$sql = "select * from city";



$source = mysql_query($sql,$conn);



$arr = array();

if($source)

{

    while($row = mysql_fetch_assoc($source))

    {

        $arr[] = $row;

    }

    mysql_free_result($source);

}

//存在get数据

if(isset($name) && isset($id) )

{

        $sql = "insert into city (name,pid) values ('$name',$id)";

        echo $sql;

        mysql_query($sql,$conn);

   }

mysql_close($conn);

//处理好的数据

$resArr = tree($arr);

//构造树类型的分级

function tree($arr,$pid = 0, $level = 0)

{

    if(empty($arr)) return ;

    static $resArr = array();



    foreach($arr as $val)

    {

        if($val['pid'] == $pid)

        {

            $val['level'] = $level;

            $resArr[] = $val;

            tree($arr,$val['id'],$level+1);

        }

    }



    return $resArr;

}



?>

<form action="./fenji.php" method="GET">

<select name="id">

<option value='0'>顶级分类</option>

<?php foreach($resArr as $val){ ?>

<option value="<?php echo $val['id'];?>"><?php echo str_repeat("  ",$val['level']) . $val['name'];?></option>

<?php } ?>

</select><input type="text" name="newCity" /><input type="submit" value="submit" />

</form>

  

你可能感兴趣的:(PHP)