问题
I am trying to turn flat mysql rows into a tree structure. Here is the id's of the categories and Sub categories
Array ( [50] => Array ( [70] => Array ( [0] => Array ( [73] => Array ( [80] => Array ( )
)
[74] => Array
(
)
[75] => Array
(
)
)
)
[71] => Array
(
[0] => Array
(
)
)
[72] => Array
(
[0] => Array
(
)
)
[73] => Array
(
[0] => Array
(
[80] => Array
(
)
)
)
[74] => Array
(
[0] => Array
(
)
)
[75] => Array
(
[0] => Array
(
)
)
[80] => Array
(
[0] => Array
(
)
)
)
[51] => Array
(
[76] => Array
(
[0] => Array
(
[77] => Array
(
)
)
)
[77] => Array
(
[0] => Array
(
)
)
[78] => Array
(
[0] => Array
(
[79] => Array
(
[81] => Array
(
)
)
)
)
[79] => Array
(
[0] => Array
(
[81] => Array
(
)
)
)
[81] => Array
(
[0] => Array
(
)
)
)
)
I wan the output in this way
<ul id="red" class="treeview-famfamfam">
<li>50
<ul> <li> 70
<ul><li> 73 <ul>
<li> 80</li></ul>
</li>
<li> 74</li>
<li>75 </li>
</ul>
</li>
<li>71</li>
<li> 72</li>
</ul>
</li>
BAsically i need to build a tree with categories sub categories sub sub .... categoreis etc. Thanks in advance
回答1:
Edited: OK. I spent half a day on this. I'm sorry to tell you this, but you'll have to change the definition of your array. Instead of an empty array for the leaf nodes, use a non-array value that has any value... Like this:
$ar=array("50" => array ( "70" => array ( "0" => array("35" => "leaf"),"3"=>"leaf" ) ) );
Then use this:
function MakeTree($array){
$return="";
if(!is_array($array)) return;
while($member=current($array)){
$return.="<li>".key($array);
$return.="<ul>".MakeTree($member)."</ul></li>";
next($array);
}
return $return;
}
$ar=array("50" => array ( "70" => array ( "0" => array("35" => "leaf"),"3"=>"leaf" ) ) );
echo(MakeTree($ar));
I don't know why, but if the leaf node has null or empty array value, it doesn't get accessed by next($array). Even if it is an empty string, so "35"=>"" won't work.
If you don't use next() and current() you can't use key(), so a change in the structure is inevitable.
来源:https://stackoverflow.com/questions/13399117/i-want-to-build-a-tree-with-this-array-these-are-the-ids-os-categories-and-su