无限循环
1.需要套2个foreach
2.2个foreach结构一样
纯代码获取数据
public function CycleData($parent_id=){
$where['parent_id']= $parent_id;
$res = $this->m->where($where)->field('id,name')->select();
foreach($res as $k=>$v){
$result[$v['id']]['id'] = $v['id'];
$result[$v['id']]['name'] = $v['name']; $r = $this->GametypeOpt($v['id']);
foreach($r as $kk=>$vv){
$result[$vv['id']]['id'] = $vv['id'];
$result[$vv['id']]['name'] = "-| ".$vv['name'];
} }
return $result; }
案例
// 无限循环数据
public function CycleData($parent_id=){
$where['parent_id']= $parent_id;
$res = $this->m->where($where)->field('id,name')->select();
foreach($res as $k=>$v){
$result[$v['id']]['id'] = $v['id'];
$result[$v['id']]['name'] = $v['name'];
//$opt[$v['id']] .= "<option value='".$v['id']."'>".$v['name']."</option>"; $r = $this->CycleData($v['id']);
foreach($r as $kk=>$vv){
$result[$vv['id']]['id'] = $vv['id'];
$result[$vv['id']]['name'] = " |- ".$vv['name'];
//$opt[$vv['id']] .= "<option value='".$vv['id']."'>".$vv['name']."</option>";
} }
return $result; }
// 无限循环opt
public function GametypeOpt($parent_id=,$val){
$list = $this->CycleData($parent_id);
$opt .= "<option value='0'>*分类</option>";
foreach($list as $k=>$v){
if($v['id'] = $val){
$opt .= "<option value='".$v['id']."' selected='selected'>".$v['name']."</option>";
}else{
$opt .= "<option value='".$v['id']."'>".$v['name']."</option>";
} }
return $opt;
}
完美代码
public function CycleData($parent_id=){
$res = $this->Catedata($parent_id);
if(empty($res)) return false;
foreach($res as $k=>$v){
$result[$v['id']]['id'] = $v['id'];
$result[$v['id']]['name'] = $v['name'];
$result[$v['id']]['parent_id'] = $v['parent_id']; $rf = $this->CycleData($v['id']);
if($rf){
foreach($rf as $k=>$vv){
$result[$vv['id']]['id'] = $vv['id'];
$result[$vv['id']]['name'] = " |- ".$vv['name'];
$result[$vv['id']]['parent_id'] = $vv['parent_id'];
}
}
}
return $result;
}
显示数组格式
array(
'' => array(
'id' => '',
'parent_id' => '',
'name' =>'*分类一'
),
'' => array(
'id' => '',
'parent_id' => '',
'name' =>' |- 二级分类一'
),
'' => array(
'id' => '',
'parent_id' => '',
'name' =>' |- |- 三级分类一'
),
'' => array(
'id' => '',
'parent_id' => '',
'name' =>'*分类一'
),
'' => array(
'id' => '',
'parent_id' => '',
'name' =>' |- 三级分类一'
), );
格式
Array
(
[] => Array
(
[id] =>
[name] =>
[child] => Array
(
[] => Array
(
[id] =>
[name] =>
[child] => Array
(
[] => Array
(
[id] =>
[name] =>
[child] =>
) ) ) ) ) [] => Array
(
[id] =>
[name] =>
[child] => Array
(
[] => Array
(
[id] =>
[name] =>
[child] =>
) ) ) )
php代码
public function CycleData($parent_id=){
$where['parent_id']= $parent_id;
$res = db('category')->where($where)->select(); if(empty($res)) return false; foreach($res as $k=>$v){
$result[$v['id']]['id'] = $v['id'];
$result[$v['id']]['name'] = $v['name'];
$result[$v['id']]['child'] = $this->CycleData($v['id']); }
return $result;
}