-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`gcid` int(11) NOT NULL AUTO_INCREMENT,
`gcname` varchar(90) DEFAULT NULL,
`parentgcid` int(11) DEFAULT NULL,
PRIMARY KEY (`gcid`),
KEY `rtrr` (`parentgcid`) USING HASH,
KEY `gff` (`gcname`) USING HASH,
KEY `gcid` (`gcid`) USING HASH
) ENGINE=MyISAM AUTO_INCREMENT=3083179 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of category
-- ----------------------------
INSERT INTO `category` VALUES ('1021', '女装', '0');
INSERT INTO `category` VALUES ('1022', '童装', '0');
INSERT INTO `category` VALUES ('1023', '其他', '0');
INSERT INTO `category` VALUES ('1024', 'T恤', '1021');
INSERT INTO `category` VALUES ('1025', '衬衫', '1021');
INSERT INTO `category` VALUES ('1026', '小衫', '1021');
INSERT INTO `category` VALUES ('1027', '毛衫', '1021');
<?php
//phpinfo();
//set_time_limit(0);
$t1 = microtime(true);
header("Content-type: text/html; charset=utf-8");
$mysql_server_name = "localhost";
$mysql_username = "root";
$mysql_password = "root";
$mysql_database = "test";
$mysql_table = "category";
#$con = @mysql_connect($mysql_server_name,$mysql_username,$mysql_password);
#if (empty($con)){
# die('Could not connect: ' . mysql_error());
#}
#$db = mysql_select_db($mysql_database,$con);
#mysql_query("set names 'utf8'");
#
$mysqli = new mysqli($mysql_server_name,$mysql_username,$mysql_password, $mysql_database);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$sql = "select * from {$mysql_table} ";
$res = $mysqli->query($sql);
if ($res) {
while($row = $res->fetch_assoc())
{
$data[] = $row;
}
#$res = treeList($data);#测试递归算法耗时110.626712秒
$res = generateTree($data);#测试引用算法耗时0.21408秒
echo"<pre>";print_r($res); #所以选择引用算法的方法实现比较好
}else{
echo '查询出错!'. $mysqli->error;
}
$mysqli->close();
$t2 = microtime(true);
echo '数据库查询耗时'.round($t2-$t1,6).'秒<br/>';
#递归算法
function treeList($data, $pid = 0)
{
$node = [];
foreach ($data as $key => $value) {
if ($pid == $value ['parentgcid']) {
$node [$key] = $value;
$node [$key] ['childs'] = array_values(treeList($data, $value ['gcid']));
}
}
return $node;
}
#引用算法
function generateTree($data){
$items = [];
foreach($data as $v){
$items[$v['gcid']] = $v;
}
$tree = [];
foreach($items as $k => $item){
if(isset($items[$item['parentgcid']])){
$items[$item['parentgcid']]['childs'][] = &$items[$k];
}else{
$tree[] = &$items[$k];
}
}
return $tree;
}
?>
网友评论