|
本帖最后由 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 */ 复制代码
|
|