Skip to content

Instantly share code, notes, and snippets.

@mig1098
Last active September 14, 2016 16:57
Show Gist options
  • Save mig1098/d4a25e6b729b9611b83bf968dbd4cbf8 to your computer and use it in GitHub Desktop.
Save mig1098/d4a25e6b729b9611b83bf968dbd4cbf8 to your computer and use it in GitHub Desktop.
<?php
function buildtree(&$result,$dropdown,$space=' ',$bool=true){
if(!is_array($dropdown) || count($dropdown) < 1 ){ return false; }
$i = 0;
$space .= $bool ? $space : '';
while($i < count($dropdown)){
$key = key($dropdown);
$result .= $space;
$result .= ( is_numeric($key) ? $dropdown[$key] : $key );
$result .= '<br />';
if(is_array($dropdown[$key])){
buildtree($result,$dropdown[$key],$space);
}
next($dropdown);
$i++;
}
}
$dropdowns = array(
'category' => array(
'men'=>array('departments','designers','surf by price','surf by size'=>array('one','two'=>array('one','two','three','four'),'three','four')),
'women'=>array('departments','designers','surf by price','surf by size'),
'handbags'=>array('styles','designers','surf by price','surf by material')
),
'condition' => array(),
'size' => array(),
'Brand' => array(),
'Pricing' => array()
);
$result = '';
$space = '-';
buildtree($result,$dropdowns,$space);
echo $result;
/*
--category
----men
--------departments
--------designers
--------surf by price
--------surf by size
----------------one
----------------two
--------------------------------one
--------------------------------two
--------------------------------three
--------------------------------four
----------------three
----------------four
----women
--------departments
--------designers
--------surf by price
--------surf by size
----handbags
--------styles
--------designers
--------surf by price
--------surf by material
--condition
--size
--Brand
--Pricing
*/
?>
<?php
function buildtree(&$result,$dropdown,$space=' ',$callback,$bool=true){
if(!is_array($dropdown) || count($dropdown) < 1 ){ return false; }
$i = 0;
$space .= $bool ? $space : '';
while($i < count($dropdown)){
$key = key($dropdown);
$result .= '<ul>';
$item = ( is_numeric($key) ? $dropdown[$key] : $key );
if(is_callable($callback)){
$result .= $callback($item,$space);
}
if(is_array($dropdown[$key])){
buildtree($result,$dropdown[$key],$space,$callback);
}
$result .= '</ul>';
next($dropdown);
$i++;
}
}
$dropdowns = array(
'category' => array(
'men'=>array('departments','designers','surf by price','surf by size'=>array('one','two'=>array('one','two','three','four'),'three','four')),
'women'=>array('departments','designers','surf by price','surf by size'),
'handbags'=>array('styles','designers','surf by price','surf by material')
),
'condition' => array(),
'size' => array(),
'Brand' => array(),
'Pricing' => array()
);
$result = '';
$space = '&nbsp;';
buildtree($result,$dropdowns,$space,function($item,$space){
return '<li>'.$item.'</li>';
});
echo $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment