打开数据库那就不写了。
前几天刚写了一个。你看下
/* 表结构
CREATE TABLE `lh_categroy` (
`id` int(10) NOT NULL auto_increment,
`parentid` int(6) NOT NULL,
`name` varchar(255) NOT NULL,
`keyword` varchar(255) NOT NULL COMMENT '关键字',
`des` varchar(255) NOT NULL COMMENT '描述',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=44 DEFAULT CHARSET=utf8
*/
/**
* 获得所有栏目排序后的列表
* @return array
*/
function getAllOrderColumns($id = 0) {
global $columns
$result = array()
if ($id) $result[$id] = $columns[$id]
foreach ($columns as $column) {
if ($column['parentid'] == $id) {
$column['level'] = 0
$result[$column['id']] = $column
getColumns($columns, $column['id'], $result, 1)
}
}
return $result
}
function getColumns($columns, $cid, &$result, $l = 1) {
foreach ($columns as $c) {
if ($c['parentid'] == $cid) {
$c['level'] = $l
$result[$c['id']] = $c
getColumns($columns, $c['id'], $result, $l + 1)
}
}
}
$sql = 'select * from lh_categroy'
$query = mysql_query($sql)
while($row = mysql_fetch_assoc($query)){
$columns[]=$row
}
$fenlei = ''
$fenlei = '<select name="cid" style="width:200pxheight:25px">
<option value="0">请选择分类</option>'
foreach(getAllOrderColumns() as $v){
$v[name] = $v[level] ? ($v[level]==1 ? '&nbsp&nbsp|-'.$v[name]:'&nbsp&nbsp&nbsp|-'.$v[name]) : $v[name]
$fenlei .= "<option value='$v[id]'>$v[name]</option>"
}
$fenlei .= '</select>'
echo $fenlei
mysql 要创建 一张用户表user,记录用户id,名称,年龄,性别,等等信息再创建一张关系表,relation表,记录 user_id,parent_id
你用php查询的时候,输入一个名称,可以取到他的user_id,根据user_id,可以查出他的父级,还可以查出父级的父级,也可以查出自己的子级,等等关系,这是一个大数组,最后遍历出来就可以了
function sumShuzi(&$tree, &$updateData = array()) {$sum = 0
// foreach($tree as $key => $item) { //这句话有毒
foreach($tree as $key => &$item) {
if(isset($item['children'])) {
$oldPshuzi = $tree[$key]['Pshuzi']
$tree[$key]['Pshuzi'] = sumShuzi($item['children'], $updateData)
if($oldPshuzi != $tree[$key]['Pshuzi']) {
$updateData[$item['id']] = array($tree[$key]['Pshuzi'], $tree[$key]['Pname_ch'])
}
}
$sum += $tree[$key]['Pshuzi']
}
return $sum
}
$tree = json_decode('[{"id":"1","Pid":"0","Pname_ch":"\u6e20\u9053\u90e8","Pshuzi":"1638000","children":[{"id":"4","Pid":"1","Pname_ch":"\u9500\u552e\u4e8c\u90e8","Pshuzi":"895000","children":[{"id":"13","Pid":"4","Pname_ch":"\u5468\u7ecf\u7406","Pshuzi":"28","children":[{"id":"28","Pid":"13","Pname_ch":"\u6e56\u5357","Pshuzi":"158000"},{"id":"35","Pid":"13","Pname_ch":"\u65b0\u7586","Pshuzi":"19000"}]},{"id":"40","Pid":"4","Pname_ch":"\u9648\u7ecf\u7406","Pshuzi":"5000"}]}]}]', true)
//$tree是具有父子关系的数据树
sumShuzi($tree, $updateData)
foreach ($updateData as $id => $item) {
$sql = "update your_table set Pshuzi={$item[0]} where id={$id}"
mysqli_query($db, $sql) //$db是你的数据库连接结果
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)