note 105354 deleted from function.create-function by danbrown
| From: | danbrown@php.net | Date: | Thu, 11 Aug 2011 14:22:50 +0000 |
| Subject: | note 105354 deleted from function.create-function by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182426@lists.php.net to get a copy of this message | ||
Note Submitter: Hayley Watson
----
phenno7 [a_t] yahoo dot com's example code makes effectively no use of create_function: one
clear indication of this is that the body of the function is a single string literal without any
part of it being constructed at runtime. It could just as easily have been written as:
<?php
$ctg_tree = array(
'1'=>array('parent_id'=>0,
'children'=>array(
'2'=>array('parent_id'=>1,
'children'=>array(
'3'=>array('parent_id'=>2))),
'4'=>array('parent_id'=>1,
'children'=>array(
'5'=>array('parent_id'=>4),
'6'=>array('parent_id'=>4))))));
function getBranchIds($tree, $ctg_id, $level = null, $arr = null, $push = false)
{
if(!$arr)
{
$arr = array();
}
if(intval($level) && $push)
{
$level--;
}
$start = false;
foreach($tree as $key=>$ctg)
{
if($push)
{
$arr[] = $key;
}
if($ctg_id == $key)
{
$start = true;
$push = true;
}
if(!empty($ctg['children']) && (intval($level) || $level === null))
{
$arr = getBranchIds($ctg['children'], $ctg_id, $level, $arr, $push);
}
if($start)
{
return $arr;
}
}
return $arr;
}
function getSubCategories($ctg_tree, $id, $level = null)
{
return getBranchIds($ctg_tree, $id, $level, null, false);
}
print_r(getSubCategories($ctg_tree, 1, 2));
?>
And would almost surely be faster (I also made some tweaks to avoid messages about uninitialised
variables and deprecated constructs).
Which is not to say it could not be simplified:
<?php
function getBranchIds($tree, $level = null)
{
$arr = array();
if($level !== 0)
{
if(isset($tree['children']))
{
foreach($tree['children'] as $key => $child)
{
$arr[] = $key;
$arr = array_merge($arr, getBranchIds($child, $level - 1));
}
}
}
return $arr;
}
function getSubCategories($ctg_tree, $id, $level = null)
{
if(isset($ctg_tree[$id]))
{
return getBranchIds($ctg_tree[$id], $level);
}
else
{
foreach($ctg_tree as $key => $ctg)
{
$arr = getSubCategories($ctg, $id, $level);
if(!empty($arr))
{
return $arr;
}
}
return array();
}
}
?>