php数组无限级树形和扁平化结构的互相转换算法函数
用例数据
$items = array( array('id' => 1, 'pid' => 0, 'name' => "江苏"), array('id' => 2, 'pid' => 0, 'name' => "浙江"), array('id' => 3, 'pid' => 1, 'name' => "南京"), array('id' => 4, 'pid' => 1, 'name' => "苏州"), array('id' => 5, 'pid' => 2, 'name' => "杭州"), array('id' => 6, 'pid' => 2, 'name' => "宁波"), );
核心函数
function arrToTree($array, $parentid = 0) { $result = array(); foreach ($array as $val) { if ($val["pid"] == $parentid) { $indata = array("id" => $val["id"], "pid" => $parentid, "name" => $val["name"]); $chidrendata = arrToTree($array, $val["id"]); if ($chidrendata) { $indata["children"] = $chidrendata; } $result[] = $indata; } } return $result; } function treeToList($arr, $parentid = 0) { $array = array(); foreach ($arr as $val) { $indata = array("id" => $val["id"], "pid" => $parentid, "name" => $val["name"]); $array[] = $indata; if (isset($val["children"])) { $children = treeToList($val["children"], $val["id"]); if ($children) { $array = array_merge($array, $children); } } } return $array; }
使用方法
$result = arrToTree($items); var_dump($result); //读取树形结构 foreach ($result as $key => $value) { var_dump($value['id'] . "=>" . $value['name']); foreach($value['children'] as $v1) { var_dump($v1); } } $list = treeToList($result); var_dump($list);