好的,这是我的递归算法:
public function getCategoryTree($tree,$return = array()) {
foreach ($tree->children as $child) {
if (count($child->children) > 0 )
$return[$tree->name] = $this->getCategoryTree($child, $return);
else
$return[] = $child->name;
}
return $return;
}
这是我要遍历的数据结构的片段
Object(stdClass)#290 (6) {
["category_id"]=>
int(1)
["parent_id"]=>
int(0)
["name"]=>
string(4) "Root"
["position"]=>
int(0)
["level"]=>
int(0)
["children"]=>
array(2) {
[0]=>
object(stdClass)#571 (7) {
["category_id"]=>
int(2)
["parent_id"]=>
int(1)
["name"]=>
string(18) "Root MySite.com"
["is_active"]=>
int(0)
["position"]=>
int(0)
["level"]=>
int(1)
["children"]=>
array(11) {
[0]=>
object(stdClass)#570 (7) {
["category_id"]=>
int(15)
["parent_id"]=>
int(2)
["name"]=>
string(9) "Widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(2)
["children"]=>
array(19) {
[0]=>
object(stdClass)#566 (7) {
["category_id"]=>
int(24)
["parent_id"]=>
int(15)
["name"]=>
string(16) "Blue widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(3)
["children"]=>
array(0) {
}
}
<snip....>
我正在尝试获得这样的 php 数据结构
categories = array( "Root" =>
array("Root MySite.com" =>
array( "Widgets" =>
// final element is NOT an array
array ("Blue Widgets", "Purple Widgets" ...)
)
)
)
我似乎无法使用我的递归算法获得我正在寻找的数据结构。任何帮助都会很棒。
最终我需要在前端再次解析并显示它,但另一天的另一个问题......