```
public function wechatmenu(){
$menu=M('weixin_menu')->where(array('menu_pid'=>0))->order('menu_id asc')->limit(3)->select();
$menu_count=M('weixin_menu')->where(array('menu_pid'=>0))->count();
// var_dump($menu_count);die;
$arr=array();
foreach ($menu as $v){
$menu_2=M('weixin_menu')->where(array('menu_pid'=>$v['menu_id']))->find();
if (!empty($menu_2)){
$v['n']=1;
}else{
$v['n']=0;
}
$arr[]=$v;
}
// var_dump($arr);die;
$k=0;
$data = '{"button":['; //菜单头
foreach($arr as $v){
if ($v['menu_type']=='click'){
$type='key';
$type_menu = $v['menu_key'];
}elseif ($v['menu_type']=='view'){
$type='url';
$type_menu = $v['menu_url'];
}
$k=$k+1;
if ($v['n']==0){
if ($k==$menu_count){
//如果是最后一个菜单,那么就不要逗号;
$data.='{"type":"'.$v['menu_type'].'","name":"'.$v['menu_name'].'","'.$type.'":"'.$type_menu.'"}';
}else{
//如果是最后一个菜单,不就要逗号了。
$data.='{"type":"'.$v['menu_type'].'","name":"'.$v['menu_name'].'","'.$type.'":"'.$type_menu.'"},';
}
}else{
$data.='{"name":"'.$v['menu_name'].'","sub_button":[';
/*
* 开始输出子菜单
*/
$menu_two=M('weixin_menu')->where(array('menu_pid'=>$v['menu_id']))->select(); //子菜单数据
$menu_twocount=M('weixin_menu')->where(array('menu_pid'=>$v['menu_id']))->count(); //子菜单数量
$m=0;
foreach ($menu_two as $y){
if ($y['menu_type']=='click'){
$type_two='key';
$type_menu_two = $y['menu_key'];
}elseif ($y['menu_type']=='view'){
$type_two='url';
$type_menu_two = $y['menu_url'];
}
// var_dump($type_two);die;
$m=$m+1;
if ($m==$menu_twocount){
//如果是最后一个菜单,不就要逗号了。
$data.='{"type":"'.$y['menu_type'].'","name":"'.$y['menu_name'].'","'.$type_two.'":"'.$type_menu_two.'"}';
}else{
//如果是最后一个菜单,不就要逗号了。
$data.='{"type":"'.$y['menu_type'].'","name":"'.$y['menu_name'].'","'.$type_two.'":"'.$type_menu_two.'"},';
}
}
if ($m==$menu_twocount){ //如果是最后一个菜单的话,就不要逗号了
$data.= ']},';
}else{
$data.= ']}';
}
}
}
$data.= ']}';
// 菜单格式 end
// echo $data;die;
return $data;
}
```