【发布时间】:2012-12-25 05:14:30
【问题描述】:
好的,这是我的递归算法:
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;
}
这是我试图遍历的数据结构的 sn-p
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" ...)
)
)
)
我似乎无法使用我的递归算法获得我正在寻找的数据结构。任何帮助 会很棒。
最终我需要在前端再次解析并显示它,但另一天的另一个问题......
【问题讨论】:
-
什么时候使用algo变得“酷”了?
-
过去 2 年的某个时候,“史诗”这个词开始流行
-
我不清楚“我正试图将它存储在 Mongo DB 中”。所以你需要一种将你的对象转换为字符串的方法???对象在序列化时可以保存为字符串。 php中有很多方法可以做到这一点。最重要的两个是:json-encode 和 serialize
-
luis 我为清楚起见编辑过,mongo db 部分无关紧要,只需要正确的 php 数据结构
标签: php data-structures recursion