用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2668|回复: 1
收起左侧

[讨论/交流] 一个不错的树形数据创建与使用

[复制链接]
发表于 2012-2-25 01:20:51 | 显示全部楼层 |阅读模式
本帖最后由 gevilrror 于 2012-2-25 01:35 编辑

很不错,两个循环就解决了问题,大牛...特地拿来分享给大家

PHP复制代码
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * $tree = build_tree_structure($categories);
 *
 * @param    array    By ref. Array of pages
 * @param    string    Id field
 * @param    string    Parent field
 *
 */

function build_tree_structure(&$categories, $id_field, $parent_field)
{
    if(!is_array($categories))
        return false;
 
    //A map is used to lookup categories quickly. Here, I also created a dummy array for the "root" level.
    $map = array(
        0 => array('childNode' => array())
    );
 
    //I added another field, subcategories, to each category array, and add it to the map.
    foreach ($categories as &$category) {
        $category['childNode'] = array();
        $map[$category[$id_field]] = &$category;
    }
 
    //Looping through each categories again, adding itself to its parent's subcategory list.
    //The reference is important here,
    //otherwise the categories already added will not be updated when there are more subcategories.
    foreach ($categories as &$category) {
        $map[$category[$parent_field]]['childNode'][] = &$category;
    }
 
    //Finally, return the subcategories of that dummy category which refer to all top level categories.
    return $map[0]['childNode'];
}
 
/**
 *
 * @param    array    By ref. trees
 * @param    string    By ref. funCallBack
 *
 */

function tree_fun_callback(&$trees, $funCallBack)
{
    if(!is_array($trees) || empty($funCallBack) || !function_exists($funCallBack))
        return ;
 
    foreach($trees as &$tree){
        $funCallBack($tree);
 
        if(isset($tree['childNode']))
            tree_fun_callback($tree['childNode'],$funCallBack);
    }
}
 
/* End of file array_helper.php */
/* Location: ./application/helpers/tree_helper.php */
复制代码

发表于 2013-5-21 22:33:26 | 显示全部楼层
真心没看懂,可能对老手可以,新手难看懂

本版积分规则