2018-03-20 php 无限级次扫描层次数据
表数据如下:
贴上代码:
<?php
/**
* file:menu.php
* author:邵德强
* date:2018-03-15
* version:1.1
*/
session_start();
function get_menu(&$menu,$allRows){
foreach($menu as $m_key=>$m_value){
foreach($allRows as $_key=>$_value){
if($m_value["id"]==$_value["parentId"]){
if(!isset($m_value["nodes"])){
$m_value["nodes"]=array();
}
$m_value["nodes"][]=$_value;
unset($allRows[$_key]);
}
}
if(isset($m_value["nodes"])){
get_menu($m_value["nodes"],$allRows);
}
$menu[$m_key]=$m_value;
}
return $menu;
}
require "../../common/connect.inc.php";
$query = "select * from my_resource";
$result = mysql_query ($query);
$allRows=array();
$menu=array();
while($row = mysql_fetch_assoc($result)){
foreach($row as $key=>$value){
if($key=="parentId"){
if($value==0){
$menu[]=$row;//对于顶层节点,先放入menu数组
}else{
//对于非顶层节点,先放入allRows数组
//以便对照menu数组中对应的父节点,加入到父节点的子节点集当中
$allRows[]=$row;
}
}
}
}
$menu=get_menu($menu,$allRows);
$json= json_encode($menu,JSON_UNESCAPED_SLASHES);
$_SESSION["json_menu_catch"]=$json;
echo $json;