问一个至今令我很头疼的问题

web实习虫 发布于 2016/01/22 22:35
阅读 416
收藏 0
PHP
$data = array(
    array("id" => 1 , "fid" => 0 , "city"=> "中国"),
    array("id" => 2 , "fid" => 1 , "city"=> "背景"),
    array("id" => 3 , "fid" => 1 , "city"=> "四川"),
    array("id" => 4 , "fid" => 1 , "city"=> "湖北"),
    array("id" => 5 , "fid" => 1 , "city"=> "安徽"),
    array("id" => 6 , "fid" => 3 , "city"=> "成都"),
    array("id" => 7 , "fid" => 3 , "city"=> "内江"),
    array("id" => 8 , "fid" => 3 , "city"=> "绵阳"),
    array("id" => 9 , "fid" => 3 , "city"=> "自贡"),
    array("id" => 0 , "fid" => 4 , "city"=> "武汉"),
)

//这是一棵树
//如何用比较简单明了的方法得到这种结构
$arr = array(
    array("爸爸",array("儿子们",array("孙子们"))....);
);

//又或者。我只拿到了上面那条二维数组 , JS怎么输出树形的枝叶



加载中
1
karsonzhang
karsonzhang

你这个$arr格式本就有问题。正确应该是

$arr = array(
    array(
        'name' => '爸爸',
        'children' => array(
            array(
                'name' => '孩子1',
                'children' => array(
                    array(
                        'name' => '子孙1-1',
                    ),
                    array(
                        'name' => '子孙1-2',
                    ),
                )
            ),
            array(
                'name' => '孩子2'
            )
        )
    )
);

要实现这样的数组,采用递归的形式即可实现

function get_children($arr, $id) {
    $newarr = array();
    if (is_array($arr)) {
        foreach ($arr as $value) {
            if ($value['fid'] == $id) {
                $value['children'] = get_children($arr, $value['id']);
                $newarr[$value['id']] = $value;
            }
        }
    }
    return $newarr;
}




0
__loong
__loong

你那种属于简易json模式。点击查看

返回顶部
顶部