不遗留问题-menu数据拼装-2

 

w




w

1
$res = array(); 2 foreach($idlist_1 as $id1) 3 { 4 $tmp = array(); 5 $tmp1 = array(); 6 $tmp1[] = $id1; 7 foreach($idlist_2 as $id2) 8 { 9 $tmp2 = array(); 10 if(get_parentid($id2)==$id1) 11 { 12 $tmp2[] = $id2; 13 $tmp3 = array(); 14 foreach($idlist_3 as $id3) 15 { 16 if(get_parentid($id3)==$id2) $tmp3[]=$id3; 17 } 18 $tmp2[] = $tmp3; 19 $tmp1[] = $tmp2; 20 } 21 } 22 $res[] = $tmp1; 23 }
  1 Array
  2 (
  3     [0] => Array
  4         (
  5             [0] => 1
  6             [1] => Array
  7                 (
  8                     [0] => 4
  9                     [1] => Array
 10                         (
 11                             [0] => 13
 12                             [1] => 14
 13                             [2] => 15
 14                         )
 15 
 16                 )
 17 
 18             [2] => Array
 19                 (
 20                     [0] => 5
 21                     [1] => Array
 22                         (
 23                             [0] => 16
 24                             [1] => 17
 25                             [2] => 18
 26                         )
 27 
 28                 )
 29 
 30             [3] => Array
 31                 (
 32                     [0] => 6
 33                     [1] => Array
 34                         (
 35                             [0] => 19
 36                             [1] => 20
 37                             [2] => 21
 38                         )
 39 
 40                 )
 41 
 42         )
 43 
 44     [1] => Array
 45         (
 46             [0] => 2
 47             [1] => Array
 48                 (
 49                     [0] => 7
 50                     [1] => Array
 51                         (
 52                             [0] => 22
 53                             [1] => 23
 54                             [2] => 24
 55                         )
 56 
 57                 )
 58 
 59             [2] => Array
 60                 (
 61                     [0] => 8
 62                     [1] => Array
 63                         (
 64                             [0] => 25
 65                             [1] => 26
 66                             [2] => 27
 67                         )
 68 
 69                 )
 70 
 71             [3] => Array
 72                 (
 73                     [0] => 9
 74                     [1] => Array
 75                         (
 76                             [0] => 28
 77                             [1] => 29
 78                             [2] => 30
 79                         )
 80 
 81                 )
 82 
 83         )
 84 
 85     [2] => Array
 86         (
 87             [0] => 3
 88             [1] => Array
 89                 (
 90                     [0] => 10
 91                     [1] => Array
 92                         (
 93                             [0] => 31
 94                             [1] => 32
 95                             [2] => 33
 96                         )
 97 
 98                 )
 99 
100             [2] => Array
101                 (
102                     [0] => 11
103                     [1] => Array
104                         (
105                             [0] => 34
106                             [1] => 35
107                             [2] => 36
108                         )
109 
110                 )
111 
112             [3] => Array
113                 (
114                     [0] => 12
115                     [1] => Array
116                         (
117                             [0] => 37
118                             [1] => 38
119                             [2] => 39
120                         )
121 
122                 )
123 
124         )
125 
126 )

 

 

 

 

w

 

php利用递归函数实现无限级分类 - 杰枫Jeff - 博客园
http://www.cnblogs.com/DeanChopper/p/4706071.html

 

create table onepiece(
    id int auto_increment,
    pid int not null,
    name varchar(225) not null,
    primary key(id)
);


insert onepiece values
    (1,0,'0_0'),
    (2,0,'0_1'),
    (3,0,'0_2'),
    (4,1,'0_0_0'),
    (5,1,'0_0_1'),
    (6,1,'0_0_2'),
    (7,2,'0_1_0'),
    (8,2,'0_1_1'),
    (9,2,'0_1_2'),
    (10,9,'0_1_2_0'),
    (11,7,'0_1_0_0'),
    (12,8,'0_1_1_0'),
    (13,8,'0_1_1_1');

 

 

 

<?php

class Unlimited
{
    protected $mysqli;

    public function __construct($config)
    {
        $this->mysqli = new mysqli($config['host'], $config['user'], $config['pwd']);
        $this->mysqli->select_db($config['db']);
        $this->mysqli->set_charset('utf8');
        if ($this->mysqli->connect_errno) {
            echo $this->mysqli->connect_error;
        }
    }

    private function getList($pid = 0, &$result = array(), $spac = 0)
    {
        $spac = $spac + 2;
        $sql = "select * from onepiece where pid={$pid}";
        $rs = $this->mysqli->query($sql);
        while ($row = $rs->fetch_assoc()) {
            $row['name'] = str_repeat('&nbsp;&nbsp', $spac) . $row['name'];
            $result[] = $row;
            $this->getList($row['id'], $result, $spac);
        }
        return $result;
    }

    /**
     * 展现下拉列表式分类
     * @return [type]
     */
    public function displayList()
    {
        $rs = $this->getList();
        $str = "<select name='cate'>";

        foreach ($rs as $key => $val) {
            $str .= "<option >{$val['name']}</option>";
        }
        $str .= "</select>";
        return $str;
    }

    private function getLink($cid, &$result = array())
    {
        $sql = "select * from onepiece where id={$cid}";
        $rs = $this->mysqli->query($sql);
        if ($row = $rs->fetch_assoc()) {
            $result[] = $row;
            $this->getLink($row['pid'], $result);
        }
        return array_reverse($result);
    }

    /**
     * 展现导航Link
     * @param  [type] $cid [description]
     * @return [type]      [description]
     */
    public function displayLink($cid)
    {
        $rs = $this->getLink($cid);
        $str = '';
        foreach ($rs as $val) {
            $str .= "<a href=''>{$val['name']}</a>>";
        }

        return $str;
    }

    /**
     * 增加分类
     * @param [type] $pid  父类id
     * @param [type] $name 本类名
     */
    public function addNodes($pid, $name)
    {
        $sql = "insert into onepiece values('',{$pid},'" . $name . "')";
        if ($this->mysqli->query($sql)) {

            return true;

        }
    }

    /**
     * 删除分类
     * @param  [type] $id 本类id
     * @return [type]
     */
    public function deleteNodes($id)
    {
        $sql = "select * from onepiece where pid ={$id}";
        $rs = $this->mysqli->query($sql);
        if ($row = $rs->fetch_assoc()) {
            $mes = "还有子元素,请勿删除";
        } else {
            $sql = "delete from onepiece where id={$id}";
            if ($this->mysqli->query($sql)) {
                $mes = "删除成功";
            }
        }
        return $mes;
    }
}

$config = array('host' => 'localhost', 'db' => 'w', 'user' => 'w', 'pwd' => 'w');
$wr = new Unlimited($config);
echo $wr->displayList();

 

 

<?php
/**
 * @name PHPTree
 * @des PHP生成树形结构,无限多级分类
 * @version 2.0.1
 * @updated 2016-08-26

 */
class PHPTree{

    protected static $config = array(
        /* 主键 */
        'primary_key'   => 'id',
        /* 父键 */
        'parent_key'    => 'parent_id',
        /* 展开属性 */
        'expanded_key'  => 'expanded',
        /* 叶子节点属性 */
        'leaf_key'      => 'leaf',
        /* 孩子节点属性 */
        'children_key'  => 'children',
        /* 是否展开子节点 */
        'expanded'      => false
    );

    /* 结果集 */
    protected static $result = array();

    /* 层次暂存 */
    protected static $level = array();
    /**
     * @name 生成树形结构
     * @param array 二维数组
     * @return mixed 多维数组
     */
    public static function makeTree($data,$options=array() ){
        $dataset = self::buildData($data,$options);
        $r = self::makeTreeCore(0,$dataset,'normal');
        return $r;
    }

    /* 生成线性结构, 便于HTML输出, 参数同上 */
    public static function makeTreeForHtml($data,$options=array()){

        $dataset = self::buildData($data,$options);
        $r = self::makeTreeCore(0,$dataset,'linear');
        return $r;
    }

    public static function getResult() {
        return self::$result;
    }

    /* 格式化数据, 私有方法 */
    private static function buildData($data,$options){
        $config = array_merge(self::$config,$options);
        self::$config = $config;
        extract($config);

        $r = array();
        foreach($data as $item){
            $id = $item[$primary_key];
            $parent_id = $item[$parent_key];
            $r[$parent_id][$id] = $item;
        }

        return $r;
    }

    /* 生成树核心, 私有方法  */
    private static function makeTreeCore($index,$data,$type='linear')
    {
        extract(self::$config);
        if(!isset($data[$index])) {
            return;
        }
        foreach($data[$index] as $id=>$item)
        {
            $itemid = $item[$primary_key];
            if($type=='normal'){
                self::$result[$itemid] = $item;
                if(isset($data[$id]))
                {
                    $item[$expanded_key]= self::$config['expanded'];
                    $item[$children_key]= self::makeTreeCore($id,$data,$type);
                }
                else
                {
                    $item[$leaf_key]= true;
                }
                $r[] = $item;
            }else if($type=='linear'){
                $parent_id = $item[$parent_key];
                self::$level[$id] = $index==0?0:self::$level[$parent_id]+1;
                $item['level'] = self::$level[$id];
                self::$result[$itemid] = $item;
                if(isset($data[$id])){
                    self::makeTreeCore($id,$data,$type);
                }

                $r = self::$result;
            }
        }
        return $r;
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=apiamz', "root", "root");

$sql = 'SELECT MAX(PurchaseDate),MIN(PurchaseDate),COUNT(*) FROM listorders';
foreach ($dbh->query($sql) as $row) {
    print_r($row);
}


$category = PHPTree::makeTree($data,[
    'primary_key' => 'cateid',
    'parent_key' => 'parentid'
]);



die();

 

 

 

DROP TABLE IF EXISTS `menu0910`;
CREATE TABLE `menu0910` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `menu` varchar(50) COLLATE utf8_unicode_ci DEFAULT '',
  `parentid` bigint(20) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- ----------------------------
-- Records of menu0910
-- ----------------------------
INSERT INTO `menu0910` VALUES ('1', '1-1', '0');
INSERT INTO `menu0910` VALUES ('2', '1-2', '0');
INSERT INTO `menu0910` VALUES ('3', '1-3', '0');
INSERT INTO `menu0910` VALUES ('4', '1-1-1', '1');
INSERT INTO `menu0910` VALUES ('5', '1-1-2', '1');
INSERT INTO `menu0910` VALUES ('6', '1-1-3', '1');
INSERT INTO `menu0910` VALUES ('7', '1-2-1', '2');
INSERT INTO `menu0910` VALUES ('8', '1-2-2', '2');
INSERT INTO `menu0910` VALUES ('9', '1-2-3', '2');
INSERT INTO `menu0910` VALUES ('10', '1-3-1', '3');
INSERT INTO `menu0910` VALUES ('11', '1-3-2', '3');
INSERT INTO `menu0910` VALUES ('12', '1-3-3', '3');
INSERT INTO `menu0910` VALUES ('13', '1-1-1-1', '4');
INSERT INTO `menu0910` VALUES ('14', '1-1-1-2', '4');
INSERT INTO `menu0910` VALUES ('15', '1-1-1-3', '4');
INSERT INTO `menu0910` VALUES ('16', '1-1-2-1', '5');
INSERT INTO `menu0910` VALUES ('17', '1-1-2-2', '5');
INSERT INTO `menu0910` VALUES ('18', '1-1-2-3', '5');
INSERT INTO `menu0910` VALUES ('19', '1-1-3-1', '6');
INSERT INTO `menu0910` VALUES ('20', '1-1-3-2', '6');
INSERT INTO `menu0910` VALUES ('21', '1-1-3-3', '6');
INSERT INTO `menu0910` VALUES ('22', '1-2-1-1', '7');
INSERT INTO `menu0910` VALUES ('23', '1-2-1-2', '7');
INSERT INTO `menu0910` VALUES ('24', '1-2-1-3', '7');
INSERT INTO `menu0910` VALUES ('25', '1-2-2-1', '8');
INSERT INTO `menu0910` VALUES ('26', '1-2-2-2', '8');
INSERT INTO `menu0910` VALUES ('27', '1-2-2-3', '8');
INSERT INTO `menu0910` VALUES ('28', '1-2-3-1', '9');
INSERT INTO `menu0910` VALUES ('29', '1-2-3-2', '9');
INSERT INTO `menu0910` VALUES ('30', '1-2-3-3', '9');
INSERT INTO `menu0910` VALUES ('31', '1-3-1-1', '10');
INSERT INTO `menu0910` VALUES ('32', '1-3-1-2', '10');
INSERT INTO `menu0910` VALUES ('33', '1-3-1-3', '10');
INSERT INTO `menu0910` VALUES ('34', '1-3-2-1', '11');
INSERT INTO `menu0910` VALUES ('35', '1-3-2-2', '11');
INSERT INTO `menu0910` VALUES ('36', '1-3-2-3', '11');
INSERT INTO `menu0910` VALUES ('37', '1-3-3-1', '12');
INSERT INTO `menu0910` VALUES ('38', '1-3-3-2', '12');
INSERT INTO `menu0910` VALUES ('39', '1-3-3-3', '12');

 

<?php

class PHPTree1
{


    function __construct($DBPrimaryKeyFieldName, $DBParentFieldName, $MinDataLevelNum = 0)
    {
        $this->MinDataLevelNum = $MinDataLevelNum;
        $this->DBPrimaryKeyFieldName = $DBPrimaryKeyFieldName;
        $this->DBParentFieldName = $DBParentFieldName;

        $this->Result = array();
        $this->LevelList = array();
    }


    public function SameLevelData($DBData)
    {
        $DBPrimaryKeyFieldName = $this->DBPrimaryKeyFieldName;
        $DBParentFieldName = $this->DBParentFieldName;
        $Arr = array();
        foreach ($DBData as $w) {
            $PrimaryKeyId = $w[$DBPrimaryKeyFieldName];
            $ParentId = $w[$DBParentFieldName];
            $Arr[$ParentId][$PrimaryKeyId] = $w;
        }
        return $Arr;
    }

    public function GetTreeResult($DBData)
    {
        $MinDataLevelNum = $this->MinDataLevelNum;
        $SameLevelDataSet = $this->SameLevelData($DBData);
        $Result = $this->MakeTreeRecursion($MinDataLevelNum, $SameLevelDataSet);
        return $Result;
    }

    private function MakeTreeRecursion($TreeIndex, $SameLevelDataSet)
    {
        $MinDataLevelNum = $this->MinDataLevelNum;
        $DBPrimaryKeyFieldName = $this->DBPrimaryKeyFieldName;
        $DBParentFieldName = $this->DBParentFieldName;
        $LevelList = $this->LevelList;
        if (!isset($SameLevelDataSet[$TreeIndex])) {
            return;
        }
        foreach ($SameLevelDataSet[$TreeIndex] as $key => $val) {
            $ParentId = intval($val[$DBParentFieldName]);
            $Level[$ParentId] = $TreeIndex == $MinDataLevelNum ? $MinDataLevelNum : self::$Level[$ParentId] + 1;
            $LevelList[$ParentId]
            $Val['level'] = self::$level[$id];
            $this->LevelSet = $this->DBParentFieldName
            self::$Result[$ValId] = $Val;
            if (isset($Data[$ValId])) {
                self::MakeTreeRecursion($id, $data, $type);
            }
            $r = self::$result;
        }
        return $r;
    }
}


try {
    $sql = 'SELECT * FROM menu0910';
    $wdata = $dbh->query($sql);
    foreach ($wdata as $row) {
        print_r($row);
    }
} catch (PDOException $w) {
    echo $w;
}


$category = PHPTree1::makeTree($wdata);

var_dump($category);

die();


/**
 * @name PHPTree
 * @des PHP生成树形结构,无限多级分类
 * @version 2.0.1
 * @updated 2016-08-26
 */
class PHPTree
{

    protected static $config = array(
        /* 主键 */
        'primary_key' => 'id',
        /* 父键 */
        'parent_key' => 'parentid',
        /* 展开属性 */
        'expanded_key' => 'expanded',
        /* 叶子节点属性 */
        'leaf_key' => 'leaf',
        /* 孩子节点属性 */
        'children_key' => 'children',
        /* 是否展开子节点 */
        'expanded' => false
    );

    /* 结果集 */
    protected static $result = array();

    /* 层次暂存 */
    protected static $level = array();

    /**
     * @name 生成树形结构
     * @param array 二维数组
     * @return mixed 多维数组
     */
    public static function makeTree($data, $options = array())
    {
        $dataset = self::buildData($data, $options);
        $r = self::makeTreeCore(0, $dataset, 'normal');
        return $r;
    }

    /* 生成线性结构, 便于HTML输出, 参数同上 */
    public static function makeTreeForHtml($data, $options = array())
    {

        $dataset = self::buildData($data, $options);
        $r = self::makeTreeCore(0, $dataset, 'linear');
        return $r;
    }

    public static function getResult()
    {
        return self::$result;
    }

    /* 格式化数据, 私有方法 */
    private static function buildData($data, $options)
    {
        $config = array_merge(self::$config, $options);
        self::$config = $config;
        extract($config);

        $r = array();
        foreach ($data as $item) {
            $id = $item[$primary_key];
            $parent_id = $item[$parent_key];
            $r[$parent_id][$id] = $item;
        }

        return $r;
    }

    /* 生成树核心, 私有方法  */
    private static function makeTreeCore($index, $data, $type = 'linear')
    {
        extract(self::$config);
        if (!isset($data[$index])) {
            return;
        }
        foreach ($data[$index] as $id => $item) {
            $itemid = $item[$primary_key];
            if ($type == 'normal') {
                self::$result[$itemid] = $item;
                if (isset($data[$id])) {
                    $item[$expanded_key] = self::$config['expanded'];
                    $item[$children_key] = self::makeTreeCore($id, $data, $type);
                } else {
                    $item[$leaf_key] = true;
                }
                $r[] = $item;
            } else if ($type == 'linear') {
                $parent_id = $item[$parent_key];
                //parent_id 0,1,2,3,4,......
                self::$level[$id] = $index == 0 ? 0 : self::$level[$parent_id] + 1;
                $item['level'] = self::$level[$id];
                self::$result[$itemid] = $item;
                if (isset($data[$id])) {
                    self::makeTreeCore($id, $data, $type);
                }

                $r = self::$result;
            }
        }
        return $r;
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=w', 'root', '');


try {
    $sql = 'SELECT * FROM menu0910';
    $wdata = $dbh->query($sql);
    foreach ($wdata as $row) {
        print_r($row);
    }
} catch (PDOException $w) {
    echo $w;
}


$category = PHPTree::makeTree($wdata);

var_dump($category);

die();

die();

 

posted @ 2016-10-03 21:31  papering  阅读(368)  评论(0编辑  收藏  举报