无限循环
1.需要套2个foreach
2.2个foreach结构一样
纯代码获取数据
public function CycleData($parent_id=0){$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=0){$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;}// 无限循环optpublic function GametypeOpt($parent_id=0,$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=0){$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('1' => array('id' => '1','parent_id' => '0','name' =>'顶级分类一'),'2' => array('id' => '2','parent_id' => '1','name' =>' |- 二级分类一'),'4' => array('id' => '4','parent_id' => '2','name' =>' |- |- 三级分类一'),'5' => array('id' => '1','parent_id' => '0','name' =>'顶级分类一'),'3' => array('id' => '3','parent_id' => '5','name' =>' |- 三级分类一'),);
格式
Array ([1] => Array([id] => 1[name] => 1[child] => Array([3] => Array([id] => 3[name] => 23523[child] => Array([2] => Array([id] => 2[name] => 234234[child] => )))))[5] => Array([id] => 5[name] => 234234[child] => Array([4] => Array([id] => 4[name] => 12302[child] => ))))
php代码
public function CycleData($parent_id=0){$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;}