<?php

$list = array(
    array('id'=>1,'pid'=>0,'label'=>'亚洲'),
    array('id'=>2,'pid'=>1,'label'=>'中国'),
    array('id'=>3,'pid'=>1,'label'=>'韩国'),
    array('id'=>4,'pid'=>1,'label'=>'日本'),
    array('id'=>5,'pid'=>2,'label'=>'北京'),
    array('id'=>7,'pid'=>2,'label'=>'广州'),
    array('id'=>8,'pid'=>7,'label'=>'天河区'),
    array('id'=>9,'pid'=>8,'label'=>'珠江新城'),
    array('id'=>10,'pid'=>3,'label'=>'首尔'),
);

$tree = buildTree($list,0);
echo json_encode($tree);

/**
* build tree
*/
function buildTree($items,$pid = 0){
    $tree = array();
    foreach($items as $node){
        if($node['pid'] === $pid){
             $node['children'] = buildTree($items,$node['id']);
             $tree[] = $node;
        }
    }
    return $tree;
}

效果如下:

 

city-tree

city-tree

Post Navigation